动态分配成员时如何设置成员的可见性?
How do I set visibility of members when they are dynamically assigned?
比方说,我们有这样一个 class:
class X {
public static function create ($a, $b) {
$x = new X();
$x->$a = $b;
return $x;
}
}
create()
动态分配成员。但是,这个成员是public:
>>> X::create("name", "Robert")
=> X {#93
+"name": "Robert",
}
>>> $x->name
=> "Robert"
有没有办法使该成员具有受保护或私有的可见性?
(在我的用例中,稍后会像上述情况那样指定成员,因此,在顶部声明 protected $some_var;
无济于事。)
没有。没有办法。在此处查看相关问题:Is there any way to set a private/protected static property using reflection classes?
唯一可能的方法是另一种方式 - 创建私有成员 public。
我不明白你想要达到什么目的,因为这是完全错误的做法,但你可以使用数组:
<?php
class Foo
{
private $data;
function __get($name)
{
if (isset($this->data[$name])) {
return $this->data[$name];
}
return null;
}
function __set($name, $value)
{
$this->data[$name] = $value;
}
}
$foo = new Foo();
$foo->var = 123;
var_dump($foo->var);
var_dump($foo);
输出如下:
int(123)
object(Foo)#1 (1) {
["data":"Foo":private]=>
array(1) {
["var"]=>
int(123)
}
}
因此您可以动态地向 class 添加属性。然后 "properties" 值存储在数组中,数组本身是私有的。如果从外部访问不存在的(或私有的)属性,则调用魔法函数 __get 和 __set。然后他们处理值的检索和设置。
在此处查看 php.net 上的文档:http://php.net/manual/en/language.oop5.magic.php
比方说,我们有这样一个 class:
class X {
public static function create ($a, $b) {
$x = new X();
$x->$a = $b;
return $x;
}
}
create()
动态分配成员。但是,这个成员是public:
>>> X::create("name", "Robert")
=> X {#93
+"name": "Robert",
}
>>> $x->name
=> "Robert"
有没有办法使该成员具有受保护或私有的可见性?
(在我的用例中,稍后会像上述情况那样指定成员,因此,在顶部声明 protected $some_var;
无济于事。)
没有。没有办法。在此处查看相关问题:Is there any way to set a private/protected static property using reflection classes?
唯一可能的方法是另一种方式 - 创建私有成员 public。
我不明白你想要达到什么目的,因为这是完全错误的做法,但你可以使用数组:
<?php
class Foo
{
private $data;
function __get($name)
{
if (isset($this->data[$name])) {
return $this->data[$name];
}
return null;
}
function __set($name, $value)
{
$this->data[$name] = $value;
}
}
$foo = new Foo();
$foo->var = 123;
var_dump($foo->var);
var_dump($foo);
输出如下:
int(123)
object(Foo)#1 (1) {
["data":"Foo":private]=>
array(1) {
["var"]=>
int(123)
}
}
因此您可以动态地向 class 添加属性。然后 "properties" 值存储在数组中,数组本身是私有的。如果从外部访问不存在的(或私有的)属性,则调用魔法函数 __get 和 __set。然后他们处理值的检索和设置。
在此处查看 php.net 上的文档:http://php.net/manual/en/language.oop5.magic.php