在 PHP 中设置 stdClass 对象的命名空间

发布于 2025-01-02 00:05:10 字数 556 浏览 4 评论 0原文

有人知道是否可以在用户定义的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅唱ヾ落雨殇 2025-01-09 00:05:10

也许您想以相反的方式执行此操作并使 stdClass-Object 的名称空间显式? ,这可以通过其中之一来完成

use \stdClass

顺便说一句

$dataObj = new \stdClass();

。 - 不,类的命名空间一旦定义就无法更改。

如果您需要访问另一个类的私有字段中的值,您可能需要检查 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

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文