0

I found something strange in the process of PHP object inheritance.

I can call NON static parent method from a subclass.

I cannot find any information about the possibility of this happening. Moreover, the PHP interpreter does not display errors.

Why it is possible? Is this normal PHP feature? Is it bad practice?

Here you are a code that you can use to test it.

<?php
class SomeParent {
    // we will initialize this variable right here
    private $greeting = 'Hello';

    // we will initialize this in the constructor
    private $bye ;

    public function __construct()
    {
        $this->bye = 'Goodbye';
    }

    public function sayHi()
    {
        print $this->greeting;
    }

    public function sayBye()
    {
        print $this->bye;
    }
    public static function saySomething()
    {
        print 'How are you?';
    }
}

class SomeChild extends SomeParent {
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Let's see what happens when we call a parent method
     * from an overloaded method of its child
     */
    public function sayHi()
    {
        parent::sayHi();
    }

    /**
     * Let's call a parent method from an overloaded method of
     * its child. But this time we will try to see if it will
     * work for parent properties that were initialized in the
     * parent's constructor
     */
    public function sayBye()
    {
        parent::sayBye();
    }
    /**
     * Let's see if calling static methods on the parent works
     * from an overloaded static method of its child.
     */
    public static function saySomething()
    {
        parent::saySomething();
    }
}

$obj = new SomeChild();
$obj->sayHi(); // prints Hello
$obj->sayBye(); // prints Goodbye
SomeChild::saySomething(); // prints How are you?
  • What is strange for you ? I don't understand it's the normal behavior of PHP. – Debflav Apr 02 '14 at 08:37
  • @Debflav there is could be confuse. `::` - operator to get access to static data, but with `parent::` you could call nonstatic methods. – sectus Apr 02 '14 at 08:43
  • Take a look at [this](http://stackoverflow.com/questions/3754786/calling-non-static-method-with) question – NorthBridge Apr 02 '14 at 08:50

2 Answers2

1

That's the way, methods of a parent class are called from subclasses in PHP. If you override a method, you often need a way to include the functionality of the parent's method. PHP provides this via the parent keyword. See http://www.php.net/manual/en/keyword.parent.php.

Callidior
  • 2,899
  • 2
  • 18
  • 28
0

This is a default functionality of PHP, In this way even after overriding the parent method, you can still add its existing functionality in child method. ex-

class vehicle {

function horn()
{
echo "poo poo";
}
}

class audi extends vehicle {
function horn()
{
parent::horn();
echo "pee pee";
}
}

$newvehicle =new audi();
$newvehicle->horn(); // this will print out "poo poo  pee pee"
sunny
  • 1,156
  • 8
  • 15