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 approac开发者_开发知识库h i chose?
thank you
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.
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.
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
}
}
}
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
精彩评论