salmane
salmane

Reputation: 4849

php OOP class variables vs object variables

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

Upvotes: 2

Views: 5642

Answers (4)

mario
mario

Reputation: 145482

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.

Upvotes: 6

Poelinca Dorin
Poelinca Dorin

Reputation: 9703

Well for star ( just for better practices ) use _ ( underscores ) if a method or property is private/protected , so you're code should look like this :

class Search 
{
    private $_variable1 = 1234;

    //example usage
    public function someMethod()
    {
        if ( $this->_variable1 == 1234 ) {
           //do smth
        }
    }
}

Upvotes: 2

RDL
RDL

Reputation: 7961

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.

Upvotes: 2

sharpner
sharpner

Reputation: 3937

in your first approach the variable is not declared private, so you can access the variable from outside the object, whereas in your second approach only allows the usage inside of the class

Upvotes: 1

Related Questions