Blue Blue - 1 year ago 59
PHP Question

What is the difference between these PHP variables

Can anyone tell me what is the differnce between:

class Test {
public $var; // I know this can be accessed from outside...

public function __construct($var) {
$this->var = $var; // This
$this->new_var = $var; // And this ... ? this is only internal like I would write private $new_var; ?

public function echoVar() {
echo $this->new_var;

Tnak you.

Answer Source

There actually won't be any fundamental difference between those two - if you write to an undeclared property in PHP (from either inside or outside the class), it will dynamically create a new public property. So given the following script:

class Test {
  public function __construct() {
    $this->foo = 'foo';

$test = new Test;
echo $test->foo;

you'll get the output foo. See

In short, properties need to be explicitly declared as private or protected if you want to hide them.

You can also implement the magic methods __get and __set on your class in order to better deal with calls to read or write dynamic properties. See the manual page on overloading for more information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download