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
The difference between object and class variables is how you can access them.
$obj->varclass::$varYour 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With