PHP - Call a parent function from a parent function in a child instance

564
April 13, 2017, at 11:48 PM

The bar function of the A class needs to call the foo function of the A class. For an instance of A, $this->bar() works. For an instance of B, $this->bar() doesn't work, it creates a loop B-foo - A-bar...

class A {
    function foo() {
        (...)
    }
    function bar() {
        $this->foo();
        (...)
    }
}
class B extends A {
    function foo() {
        parent::bar();
        (...)
    }
    function bar() {
        $this->foo();
        (...)
    }
}

I tried such workaround for the 'A' bar function, but getting error : "Cannot access parent:: when current class scope has no parent"

class A{
    function bar(){
        switch ( get_class($this) )
        {
            case "A" : $this->foo() ; break;
            case "B" : parent::foo(); break;
        }
    } 
}

Any idea of how to do this?

Thanks

Answer 1

You cann use self

class A {
    function foo() {
        print __METHOD__;
    }
    function bar() {
        print __METHOD__;
        self::foo();
    }
}
class B extends A {
    function foo() {
        print __METHOD__;
        parent::bar();
    }
    function bar() {
        print __METHOD__;
        $this->foo();
    }
}
(new A)->bar();//calls  A::bar A::foo
(new A)->foo();//calls  A::foo
(new B)->bar();//calls  B::bar B::foo A::bar A::foo
(new B)->foo();//calls  B::foo A::bar A::foo
Rent Charter Buses Company
READ ALSO
JSON image set to FALSE

JSON image set to FALSE

I'm using the php code below to display an image using it's URL which is written in a JSON file

421
Like system php mysql jquery

Like system php mysql jquery

I have a page with the post and a "like" button, when I click the button "like" I would to change it in "dislike", my code in here:

433
uploading mp4 with PHP

uploading mp4 with PHP

Hello guyys i am tring to upload mp4 file with php from 2 days

523