To access public property of object in php, just use $obj->propertyname like:
class MyClass { public $a; }; $my=new MyClass; $my->a=1; echo $my->a;
Note that, unlike C++, you cannot use MyClass $my to create an instance of a class. You must use $my=new MyClass to initialize an object.
Unlike C++, you do not need to declare a variable in a class to use it:
class MyClass { }; $my=new MyClass; $my->a=1; echo $my->a;
When accessing an undeclared property, the __set function, if defined, will be called:
class MyClass { public function __set($name,$value)//called { echo "set $name<br>"; return $this->$name=$value; } }; $my=new MyClass; $my->a=1; echo $my->a;
This does not apply to a declared (public) property:
class MyClass { public $a; public function __set($name,$value) //not called { echo "set $name<br>"; return $this->$name=$value; } }; $my=new MyClass; $my->a=1; echo $my->a;
But the __set function is called when writing to a (declared) private/protected property:
class MyClass { private $a; public function __set($name,$value) // called { echo "set $name<br>"; return $this->$name=$value; } }; $my=new MyClass; $my->a=1; echo $my->a;//fatal error
The reading of the private/protected property still fails with a fatal error. To read a private/protected property using the $obj->propertyname syntax, you need a getter function:
class MyClass { private $a; public function __get($name) { echo "get $name<br>"; return $this->a; } public function __set($name,$value) // called { echo "set $name<br>"; return $this->$name=$value; } }; $my=new MyClass; $my->a=1; echo $my->a;
Note that the setter function takes exactly two arguments, and the getter function must take exactly 1 argument, and we did not call the setter function __set and the getter function __get explicitly. They are called implicitly.