Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php OOP class variables vs object variables

Tags:

oop

php

when making a class in php what is the difference between these two :

class Search 

    function __construct()
    {

        $this->variable1= 1234;      

    }
}

and

class Search 

    private $variable1;

$variable1=1234;

    function __construct()
    {

    }
}

if i need to access a value across different methods does it make any difference which approach i chose?

thank you

like image 392
salmane Avatar asked Dec 06 '25 04:12

salmane


2 Answers

The difference between object and class variables is how you can access them.

  • object variable: $obj->var
  • class variable: class::$var

Your class definition should be:

class Search {
    static $variable = 2;   // only accessible as Search::$variable
}

Versus:

class Search2 {
    var $variable = "object_prop";
}

Wether you use var or public or the private access modifier is not what makes a variable an object property. The deciding factor is that it's not declared static, because that would make it accessible as class variable only.

like image 162
mario Avatar answered Dec 08 '25 18:12

mario


The are essentially the same thing however if you do not declare the variable/property before it is called you will get a warning saying the variable doesn't exist.

It is best practice to do it this way:

class Search {

  private $_variable1;

  function __construct() {
    $this->_variable1=1234;
  }

}

Note: private variables are only available to the class they are declared in.

like image 31
RDL Avatar answered Dec 08 '25 17:12

RDL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!