PHP 自动属性/重载
我正在写一些PHP。我有几个类没有声明任何属性,无论是公共的还是其他的。我有一个自定义 mySQL 类,它从 mySQL 获取对象并为新初始化的 PHP 对象设置属性值,如下所示...
while ($row = mysql_fetch_assoc($result))
{
foreach($row as $key => $value)
{
$this->{$key} = $value;
}
}
这似乎工作正常,因为我可以在任何地方调用所述属性... $ this->my_auto_property
等。我找不到任何 PHP 文档将其描述为重载类对象属性的方法。
这样可以吗?我想确保它不会在 PHP 的未来版本中消失的某种向后兼容性。
I am writing some PHP. I have several classes that do not declare any properties, public or otherwise. I have a custom mySQL class that fetches objects from mySQL and sets property values for the newly init'd PHP object like so...
while ($row = mysql_fetch_assoc($result))
{
foreach($row as $key => $value)
{
$this->{$key} = $value;
}
}
This seems to work fine as I can then call said properties anywhere I please ... $this->my_auto_property
etc. I cannot find any PHP docs that describe this as a way to overload a class object's properties.
Is this okay? I want to make sure it's not some sort of backwards compatibility that will evaporate in future releases of PHP.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不会重载任何属性,它只是使用可变变量设置属性。动态创建新属性一直是 PHP 的一个特性。当然,没有人能保证它不会被弃用,但 PHP 支持弱类型的方式我认为这不太可能。
另一种方法是将值存储在数组中并创建一个神奇的
__get
访问器如果您想增加封装性和对可访问性的控制,请阅读它们。This is not overloading any property, it's just setting a property using variable variables. Dynamically creating new properties has always been a feature of PHP. Of course, nobody can guarantee that it won't be deprecated, but the way PHP favors weak typing I'd say that's unlikely.
An alternative would be to store the values in an array and create a magic
__get
accessor to read them, if you want to increase encapsulation and your control over accessibility.尝试这样的事情:
Try something like this: