the code is self-explanatory, but the problem is, that I can't override the static variable through method calls, so the static variable of the class gives a value, but the value that I get through the objects is different.
Class dbEntity {
protected static $connection;
private static $name = "dbEntity";
public static function getName() {
return self::$name;
}
public static function setConnection($connection) {
self::$connection = $connection;
}
public static function getConnection() {
return self::$connection;
}
}
Class Patient extends dbEntity {
public static $connection = "patientConnection";
public static $name = "Patient";
}
$p = new Patient();
$p->setConnection("myConnection");
echo $p->getConnection() . "\n"; //myConnection
echo Patient::$connection . "\n"; //patientConnection
echo $p->getConnection() . "\n"; //myConnection
CodePudding user response:
Ulrich is correct, if you change the following lines from self::
to static::
the code works as you're expecting it to.
public static function getName() {
return static::$name;
}
public static function setConnection($connection) {
static::$connection = $connection;
}
public static function getConnection() {
return static::$connection;
}
...
echo $p->getConnection() . "<br>"; //myConnection
echo Patient::$connection . "<br>"; //myConnection
echo $p->getConnection() . "<br>"; //myConnection
CodePudding user response:
You need late static binding, see the official documentation: https://www.php.net/manual/en/language.oop5.late-static-bindings.php