How can I correctly call the implementation of an abstract function from the parent class? The problem is that I don't quite understand static
and I don't know if I should do it with static
or $this
.
<?php
abstract class ParentClass{
abstract protected function createArray();
public function printArray(){
// ACA LLAMO A MI FUNCIÓN ABSTRACTA
// OPCIÓN 1
print_r(static::createArray());
// OPCIÓN 2
print_r($this->createArray());
}
}
class ChildClass extends ParentClass{
protected function createArray(){
return [1,2,3,4];
}
}
$c = new ChildClass();
$c->printArray();
I understand the following, you can correct me if I'm wrong.
self
: It refers to the same class at runtime where the word is written, so if I call the abstract function with in my parent class, self
it will give me an error, since it will call its definition.
$this
: It refers to the instance of the object, in this case the instance will already have the implementation of the method and that is why it will work.
From what I've read I static
prefer the instantiated class, in this case the child and that's why it works.
Can anyone give me a simple answer of what it really is static
?
static
and are $this
they the same? if not the same... How are they different?
Finally I have noticed that with static
you can call static properties and methods, while with $this
not.
After further searching I have come to a more solid conclusion of what it really is
static
static::
refers to late static bindings, these attempt to resolve the limitationself::
by introducing a keyword (static
) that references the class that was initially called at runtime .In this case, the class that was initially called was the child class, so it behaves similarly to
$this
.Read more about Late Static Links
Brief explanation
static
and$this
they are completely differentstatic
,public
private
orprotected
they are Access Modifiers either to properties or functions and the$this
orself
andparent
( Resolution Operator ) refers to the instance to execute a property or function.Regarding your question you need to use
parent
to call the function or property of the class that you extend your class.more information