如何动态创建新属性 [英] How to create new property dynamically

查看:106
本文介绍了如何动态创建新属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从对象方法内的给定参数创建属性?

How can I create a property from a given argument inside a object's method?

class Foo{

  public function createProperty($var_name, $val){
    // here how can I create a property named "$var_name"
    // that takes $val as value?

  }

}

并且我希望能够访问以下属性:

And I want to be able to access the property like:

$object = new Foo();
$object->createProperty('hello', 'Hiiiiiiiiiiiiiiii');

echo $object->hello;

我还可以将财产设置为公共/受保护/私有吗?我知道在这种情况下它应该是公开的,但是我可能想添加一些魔术方法来获取受保护的属性和内容:)

Also is it possible that I could make the property public/protected/private ? I know that in this case it should be public, but I may want to add some magik methods to get protected properties and stuff :)


我想我找到了解决方法:


I think I found a solution:

  protected $user_properties = array();

  public function createProperty($var_name, $val){
    $this->user_properties[$var_name] = $val;

  }

  public function __get($name){
    if(isset($this->user_properties[$name])
      return $this->user_properties[$name];

  }

您认为这是个好主意吗?

do you think it's a good idea?

推荐答案

有两种方法可以做到这一点.

There are two methods to doing it.

一个,您可以直接从类外部动态创建属性:

One, you can directly create property dynamically from outside the class:

class Foo{

}

$foo = new Foo();
$foo->hello = 'Something';

或者如果您希望通过createProperty方法创建属性:

Or if you wish to create property through your createProperty method:

class Foo{
    public function createProperty($name, $value){
        $this->{$name} = $value;
    }
}

$foo = new Foo();
$foo->createProperty('hello', 'something');

这篇关于如何动态创建新属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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