0

Consider this sample code

<?php
class MyAwesomeClass {
    public $myawesomeproperty = 'test';

    public function __construct() {
        $self = new stdClass();

        $self->myawesomeproperty = "hello guys!";
    }
}

$test_obj = new MyAwesomeClass();

echo '<pre>';
var_export( $test_obj );
echo '</pre>';
?>

It's supposed to set "myawesomeproperty" to a new string so var_export shows "hello guys!" in the output.

What I'm actually getting is

MyAwesomeClass::__set_state(array(
   'myawesomeproperty' => 'test',
))

Apparently the construct function does not save anything to actual object.

Why is this happening? What am I missing?

miken32
  • 42,008
  • 16
  • 111
  • 154
L1Q
  • 15
  • 1
  • 3

2 Answers2

1

You're setting the property of a local variable called $self. If you want to change the object's property, use $this instead:

<?php
class MyAwesomeClass {
    public $myawesomeproperty = 'test';

    public function __construct() {
        $this->myawesomeproperty = "hello guys!";
    }
}

$test_obj = new MyAwesomeClass();

echo '<pre>';
var_export( $test_obj );
echo '</pre>';
?>
miken32
  • 42,008
  • 16
  • 111
  • 154
  • Ok, you are right, I mistakenly used "$self->" thinking it would work like "self::" but with public properties, now [this](http://stackoverflow.com/questions/151969/when-to-use-self-over-this) actually cleared my mind completely.Thanks for your answer. The most stupid mistakes are so obvious when pointed at :D – L1Q Feb 18 '17 at 19:30
1

You are creating a different object ($self) inside the constructor. You aren't doing anything with it, so the object is removed from memory when php leaves the function scope.

To overwrite a property of the object attached to the current function scope, use $this->myawesomeproperty="Hello Guys";

Ruben Vincenten
  • 807
  • 4
  • 7