Search code examples
phplanguage-construct

How can I run a method from an object's parent class that has been overridden in PHP?


This may be a duplicate post, but searching for the answer just led me to the C, Java and ColdFusion ways of doing this...

Given class A with method foo() and class B extends A and also has foo(), I want to run something like:

$b = new B();
$b->A::foo(); (this is working C syntax, but that doesn't seem to work)

Solution

  • You can't call it directly from the object, you have to call it from within A->foo(), for example:

    class A 
    {
        function foo() 
        {
            echo "I am A::foo() and provide basic functionality.<br />\n";
        }
    }
    
    class B extends A 
    {
        function foo() 
        {
            parent::foo();
        }
    }
    
    $b = new B;
    $b->foo();