Why does PHP allow you to do this:
<?php
class Doge
{
public function dogeMember()
{
echo "Hello From Doge\r\n";
$this->nonDogeMember();
}
}
class DogeCoin extends Doge
{
public function nonDogeMember()
{
echo "Hello from DogeCoin\r\n";
}
}
$d = new DogeCoin;
$d->dogeMember();
Apparently, from the opcode, the $this variable is ignored and the call is made as if the method were on the DogeCoin class.
In one sentence: $this is a reference to the current object instance.
An object is/may be composed of several things, including methods and properties of several inherited classes, traits and dynamically added members. Only the "composite" result of all inheritance and dynamic modification during runtime is what makes up the final object instance.
The actual call $this->nonDogeMember() is only resolved at runtime. Since the object it's being called on ($d) has that method (through inheritance), everything's fine.
Having said that, you should not write this kind of code, because there indeed is no guarantee that this method will exist at runtime and may produce a runtime error. To avoid this, you should define your class and that method as abstract:
abstract class Doge {
public function dogeMember() {
echo "Hello From Doge\r\n";
$this->nonDogeMember();
}
abstract public function nonDogeMember();
}
This is PHP's way to help you ensure such runtime errors won't happen, or at least they'll be caught at an earlier point in (run)time and produce an easier to trace error.
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