1

Anyone know how to assign stdClass value to variable?

I have a stdClass object and when I print it using var_dump($userdetails->emailaddress), it does print out the value as String(31)"[email protected]";

but when I try to assign the object value to variable, lets say:

$to = $userdetails->emailaddress; 

the $to value become NULL ...

Anyone can help ?

2
  • 1
    That should work fine. For example, try: php -r '$x = new stdClass; $x->foo = "bar"; $foo = $x->foo; var_dump($foo);' It will print "bar". Paste your actual code, there's probably something else wrong with it. Commented Aug 9, 2010 at 10:39
  • This should work. Can you provide a complete example that displays the incorrect behavior? Have you checked that it's not an identifier case issue (such as $userDetails instead of $userdetails) ? Commented Aug 9, 2010 at 10:41

3 Answers 3

5

That sounds like you are doing something wrong, because

$obj = new StdClass;
$obj->email = '[email protected]';
$to = $obj->email;
var_dump($to); // string(15) "[email protected]"

Note that variables and object members in PHP are case sensitive (unlike functions and methods), so

$to = $obj->eMail;
var_dump($to); // NULL

However, in this case you also receive a PHP Notice

Notice: Undefined property: stdClass::$eMail

It is good practise to enable error_reporting(-1) and the PHP.ini directives display_errors and display_startup_errors on development machines.


Since it's a CW. feel free to use this space for further debugging tips

Sign up to request clarification or add additional context in comments.

Comments

0

I think there nothing wrong / prevent from assign value from stdClass to variable. Pls check the spelling of the code.

Comments

0

Is the var public or not?

If the class is made like:

class Example
{
    public $emailaddress;

    public function example()
    {
        #do something
    }  

}

Then I can't see why there would be an issue.

2 Comments

It's a StdClass so any other visibility than public should not apply
Ah, I have never used a StdClass so I just assumed it was an example name. My bad blush

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.