你可以在PHP中动态创建实例属性吗? [英] Can you create instance properties dynamically in PHP?

查看:79
本文介绍了你可以在PHP中动态创建实例属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法动态创建所有实例属性?例如,我想能够生成构造函数中的所有属性,并且仍然能够在类实例化后访问它们,如下所示: $ object-> property 。注意,我想单独访问属性,而不使用数组;这里是我不想要的示例:

Is there any way to create all instance properties dynamically? For example, I would like to be able to generate all attributes in the constructor and still be able to access them after the class is instantiated like this: $object->property. Note that I want to access the properties separately, and not using an array; here's an example of what I don't want:

class Thing {
    public $properties;
    function __construct(array $props=array()) {
        $this->properties = $props;
    }
}
$foo = new Thing(array('bar' => 'baz');
# I don't want to have to do this:
$foo->properties['bar'];
# I want to do this:
//$foo->bar;

更具体地说,当我处理具有大量属性的类时,我希望能够选择每个列值应存储在一个单独的实例属性中。

To be more specific, when I'm dealing with classes that have a large number of properties, I would like to be able to select all columns in a database (which represent the properties) and create instance properties from them. Each column value should be stored in a separate instance property.

推荐答案

sort。有些魔法方法可以让你自己的代码在运行时实现类的行为:

Sort of. There are magic methods that allow you to hook your own code up to implement class behavior at runtime:

class foo {
  public function __get($name) {
    return('dynamic!');
  }
  public function __set($name, $value) {
    $this->internalData[$name] = $value;
  }
}

这是一个动态getter和setter方法的例子,它允许你在访问对象属性时执行行为。例如

That's an example for dynamic getter and setter methods, it allows you to execute behavior whenever an object property is accessed. For example

print(new foo()->someProperty);

将打印,在这种情况下为动态!并且还可以为任意命名的属性分配值,在这种情况下,将静默调用__set()方法。 __call($ name,$ params)方法对于对象方法调用也是一样。在特殊情况下非常有用。但大多数时候,你会得到:

would print, in this case, "dynamic!" and you could also assign a value to an arbitrarily named property in which case the __set() method is silently invoked. The __call($name, $params) method does the same for object method calls. Very useful in special cases. But most of the time, you'll get by with:

class foo {
  public function __construct() {
    foreach(getSomeDataArray() as $k => $value)
      $this->{$k} = $value;
  }
}

...因为大多数情况下,将数组的内容转储到相应命名的类字段中一次,或至少在执行路径中的非常明确的点。所以,除非你真的需要动态行为,使用最后一个例子来填充你的对象的数据。

...because mostly, all you need is to dump the content of an array into correspondingly named class fields once, or at least at very explicit points in the execution path. So, unless you really need dynamic behavior, use that last example to fill your objects with data.


这被称为重载
http://php.net/manual/en/language.oop5.overloading。 php

这篇关于你可以在PHP中动态创建实例属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆