在 PHP 中为 stdClass 对象设置命名空间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9113930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting namespace for stdClass object in PHP
提问by Skittles
Would anyone happen to know if it's possible to set a namespace on a user-defined stdClass object.
有人会碰巧知道是否可以在用户定义的 stdClass 对象上设置命名空间。
What I would like to do is to return all the private properties of a class as an object in the form of a getter method.
我想做的是以getter方法的形式将类的所有私有属性作为对象返回。
I found one possible solution where I could do something like this;
我找到了一种可能的解决方案,我可以做这样的事情;
public function getDataItems() {
$dataObj = new stdClass;
$dataObj->image_id = $this->image_id;
$dataObj->image_name = $this->image_name;
$dataObj->name = $this->name;
$dataObj->email = $this->email;
$dataObj->company = $this->company;
return $dataObj;
}
The only problem I have though is that the class that this function lives in is using a namespace and therefore I need to somehow assign the same namespace to this $dataObj object.
我唯一的问题是这个函数所在的类正在使用命名空间,因此我需要以某种方式将相同的命名空间分配给这个 $dataObj 对象。
Does anyone know how I can do this or if it's even possible?
有谁知道我该怎么做,或者甚至可能吗?
回答by Martin Schuhfu?
maybe you want to do this the other way round and make the namespace of the stdClass-Object explicit? This could be done by either
也许您想反过来这样做并使 stdClass-Object 的命名空间显式?这可以通过以下任一方式完成
use \stdClass
or
或者
$dataObj = new \stdClass();
btw. - no, it is not possible to change the namespace of a class once it was defined.
顺便提一句。- 不,一旦定义了类的命名空间,就不可能更改它。
You might want to check up on the ReflectionProperty
built-in class if you need to access values form a private field of another class (see http://php.net/manual/en/reflectionproperty.getvalue.php).
ReflectionProperty
如果您需要从另一个类的私有字段访问值,您可能需要检查内置类(请参阅http://php.net/manual/en/reflectionproperty.getvalue.php)。