Ale*_*lex 66 php properties object
如何从对象方法中的给定参数创建属性?
class Foo{
public function createProperty($var_name, $val){
// here how can I create a property named "$var_name"
// that takes $val as value?
}
}
Run Code Online (Sandbox Code Playgroud)
我希望能够访问该属性,如:
$object = new Foo();
$object->createProperty('hello', 'Hiiiiiiiiiiiiiiii');
echo $object->hello;
Run Code Online (Sandbox Code Playgroud)
还有可能我可以将该属性设为public/protected/private吗?我知道在这种情况下它应该是公开的,但我可能想添加一些magik方法来获取受保护的属性和东西:)
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];
}
Run Code Online (Sandbox Code Playgroud)
你认为这是个好主意吗?
mau*_*ris 96
有两种方法可以做到这一点.
一,您可以从类外部动态直接创建属性:
class Foo{
}
$foo = new Foo();
$foo->hello = 'Something';
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望通过您的createProperty方法创建属性:
class Foo{
public function createProperty($name, $value){
$this->{$name} = $value;
}
}
$foo = new Foo();
$foo->createProperty('hello', 'something');
Run Code Online (Sandbox Code Playgroud)
属性重载非常慢.如果可以的话,尽量避免它.同样重要的是实现另外两种魔术方法:
__isset(); __unset();
如果您不想在以后使用这些对象"属性"时发现一些常见错误
这里有些例子:
http://www.php.net/manual/en/language.oop5.overloading.php#language.oop5.overloading.members
亚历克斯评论后编辑:
您可以自己检查两个解决方案之间的时间差异(更改$ REPEAT_PLEASE)
<?php
$REPEAT_PLEASE=500000;
class a {}
$time = time();
$a = new a();
for($i=0;$i<$REPEAT_PLEASE;$i++)
{
$a->data = 'hi';
$a->data = 'bye'.$a->data;
}
echo '"NORMAL" TIME: '.(time()-$time)."\n";
class b
{
function __set($name,$value)
{
$this->d[$name] = $value;
}
function __get($name)
{
return $this->d[$name];
}
}
$time=time();
$a = new b();
for($i=0;$i<$REPEAT_PLEASE;$i++)
{
$a->data = 'hi';
//echo $a->data;
$a->data = 'bye'.$a->data;
}
echo "TIME OVERLOADING: ".(time()-$time)."\n";
Run Code Online (Sandbox Code Playgroud)
使用语法:$ object - > {$ property}其中$ property是一个字符串变量,$ object可以是这个,如果它在类或任何实例对象中
实例:http: //sandbox.onlinephpfunctions.com/code/108f0ca2bef5cf4af8225d6a6ff11dfd0741757f
class Test{
public function createProperty($propertyName, $propertyValue){
$this->{$propertyName} = $propertyValue;
}
}
$test = new Test();
$test->createProperty('property1', '50');
echo $test->property1;
Run Code Online (Sandbox Code Playgroud)
结果:50
以下示例适用于那些不想声明整个类的人.
$test = (object) [];
$prop = 'hello';
$test->{$prop} = 'Hiiiiiiiiiiiiiiii';
echo $test->hello; // prints Hiiiiiiiiiiiiiiii
Run Code Online (Sandbox Code Playgroud)