According to php, class::self always points to the class itself, but as I wrote down these codes, something strange happens:
class C_foo{
function foo() { return "foo() from C_foo"; }
function bar() { echo self::foo(); }
}
class C_bar extends C_foo{
function foo() { return "foo() from C_bar"; }
}
C_foo::bar();
C_bar::bar();
I thought the output would have been:
foo() from C_foo
foo() from C_bar
But in fact:
foo() from C_foo
foo() from C_foo
It means that the self in parent class does NOT exactly inherit into the child, it works more like to this:
foo() {return parent::foo();}
Is that a feature from php or is it a bug? Or is it mean to be like this?
Otherwise, such thing is occurred as I tried to tell a class create objects from itself, the code is something like this:
class Models {
function find($exp) {
...
...
$temp_model = new self();
...
...
}
}
class Something extends Models {...}
$somethings = Something::find("...");
Maybe someone would ask, "why don't you set a variable with the value of class, and use the variable as the __construction function?"
Like this:
...
...
function find($exp) {
...
...
$class_name = __class__;
$temp_model = new $class_name();
...
...
}
...
In fact I did that, and got a even more weird result:
It works only when the class does not have any property or function but find()
, or an error telling me a variable shows off where a function sould exist would jump out.
Inheritance concept is to inherit properties from one class to another but not vice versa. But since parent class reference variable points to sub class objects. So it is possible to access child class properties by parent class object if only the down casting is allowed or possible....
The inherited methods can be used directly as they are. You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
The class whose properties and methods are inherited is known as the Parent class. And the class that inherits the properties from the parent class is the Child class. The interesting thing is, along with the inherited properties and methods, a child class can have its own properties and methods.
multiple inheritance allows a child class to inherit from more than one parent class.
It sounds like you're describing the PHP feature known as 'late static binding'.
PHP provides two syntaxes: self::
and static::
.
static
was introduced in PHP 5.3 because a lot of people expected self
to work the you're describing.
See the PHP manual for more: http://php.net/manual/en/language.oop5.late-static-bindings.php
You can also use the syntax new self()
or new static()
to create new instances:
$parent = new self();
$child = new static();
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