class database{
protected $db;
protected function connect(){
$this->db = new mysqli( /* DB info */ ); // Connecting to a database
}
}
class example extends database{
public function __construct(){
$this->connect();
}
public static function doQuery(){
$query = $this->db->query("theQuery"); // Not working.
$query = self::$db->query("theQuery"); // Not working.
$query = parent::$db->query("theQuery"); // Also not working.
}
}
I want to do something like that but I cant find a way that works, The property has to static...
A static method can only access static data members and static methods of another class or same class but cannot access non-static methods and variables. Also, a static method can rewrite the values of any static data member.
The only way to access a non-static variable from a static method is by creating an object of the class the variable belongs to.
Consequently, attempting to access a non-static variable from a static context (a static method or block) without a class instance creates ambiguity—every instantiated object has its own variable, so the compiler is unable to tell which value is being referenced.
To access a non-static property or method, you append the object operator to $this keyword. To access static properties or methods inside the class, you use the self keyword followed by the scope resolution, or the double-colon, operator.
You may access by instantiating a new object ($self = new static;
). The sample code:
class Database{
protected $db;
protected function connect(){
$this->db = new mysqli( /* DB info */ ); // Connecting to a database
}
}
class Example extends Database{
public function __construct(){
$this->connect();
}
public static function doQuery(){
$self = new static; //OBJECT INSTANTIATION
$query = $self->db->query("theQuery"); // working.
}
}
This is the same as calling
$self = new Example;
but more programmatically, if the class name is ever changed it does not need updating.
You cannot access non-static properties from static methods. Non-static properties belong only to instantiated objects, where every instantiated object has a separate property value.
I will illustrate on an example, this code doesn't work:
class Example {
public $a;
public function __construct($a) {
$this->a = $a;
}
public static function getA() {
return $this->a;
}
}
$first = new Example(3);
$second = new Example(4);
// is $value equal to 3 or 4?
$value = Example::getA();
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