Setting namespace for stdClass object in PHP
Asked Answered
N

1

29

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?

Nomothetic answered 2/2, 2012 at 14:23 Comment(0)
D
85

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

Dania answered 2/2, 2012 at 14:31 Comment(3)
So, if the class that the above method resides in is using namespace foo; I can't make the $dataObj use that same namespace then?Nomothetic
$dataObj = new \stdClass(); That did the trick! Thank you, marvesmith! :)Nomothetic
PHP doc on namespaces: nl.php.net/manual/en/language.namespaces.basics.phpTidings

© 2022 - 2024 — McMap. All rights reserved.