Still trying to figure out oop in PHP5. The question is, how to access a parent's static variable from an extended class' method. Example below.
<?php
error_reporting(E_ALL);
class config {
public static $base_url = 'http://example.moo';
}
class dostuff extends config {
public static function get_url(){
echo $base_url;
}
}
dostuff::get_url();
?>
I thought this would work from experience in other languages.
In the static method,properties are for the class, not the object. This is why access to static methods or features is possible without creating an object. $this refers to an object made of a class, but $self only refers to the same class.
In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class.
$var1 = 'Variable 1'; $var2 = 'Variable 2'; class myClass { function __construct() { $this->var1 = $GLOBALS['var1']; $this->var2 = $GLOBALS['var2']; } public function returnVars() { return $this->var1 .
There are no global variables in C#. A variable is always locally-scoped. The fundamental unit of code is the class, and within a class you have fields, methods, and properties. You can mimic a "global variable" by making a public static field or property in some class, but you shouldn't.
It's completely irrelevant that the property is declared in the parent, you access it the way you access any static property:
self::$base_url
or
static::$base_url // for late static binding
Yes, it's possible, but actually should be written like this:
class dostuff extends config {
public static function get_url(){
echo parent::$base_url;
}
}
But in this case you can access it both with self::$base_url
and static::$base_url
- as you don't redeclare this property in the extending class. Have you done it so, there would have been a distinction:
self::$base_url
would always refer to the property in the same class that line's written, static::$base_url
to the property of the class the object belongs to (so called 'late static binding').Consider this example:
class config {
public static $base_url = 'http://config.example.com';
public function get_self_url() {
return self::$base_url;
}
public function get_static_url() {
return static::$base_url;
}
}
class dostuff extends config {
public static $base_url = 'http://dostuff.example.com';
}
$a = new config();
echo $a->get_self_url(), PHP_EOL;
echo $a->get_static_url(), PHP_EOL; // both config.example.com
$b = new dostuff();
echo $b->get_self_url(), PHP_EOL; // config.example.com
echo $b->get_static_url(), PHP_EOL; // dostuff.example.com
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