在 PHP 中设置 stdClass 对象的命名空间
有人知道是否可以在用户定义的 stdClass 对象上设置命名空间。
我想做的是以 getter 方法的形式将类的所有私有属性作为对象返回。
我找到了一个可能的解决方案,我可以做这样的事情;
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;
}
我遇到的唯一问题是这个函数所在的类正在使用命名空间,因此我需要以某种方式将相同的命名空间分配给这个 $dataObj 对象。
有谁知道我该怎么做或者是否可能?
Would anyone happen to know if it's possible to set a namespace on a user-defined stdClass object.
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.
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.
Does anyone know how I can do this or if it's even possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许您想以相反的方式执行此操作并使 stdClass-Object 的名称空间显式? ,这可以通过其中之一来完成
顺便说一句
。 - 不,类的命名空间一旦定义就无法更改。
如果您需要访问另一个类的私有字段中的值,您可能需要检查
ReflectionProperty
内置类(请参阅 http://php.net/manual/en/reflectionproperty.getvalue.php)。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
or
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).