Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call object method from child object(PHP)

Tags:

oop

php

Say object of class B is attribute of class A. How can I call method of object of class A from method of object of class B? What would be nice solution without passing object link?

Thanks!

Here goes code sample:

class A{
    var $b;

    function __construct(){
        $this->b = new B();
    }

    function f1(){
        $this->b->f3();
    }        

    function f2(){
        echo 'hello!';
    }
}

class B{
    function f3(){
         // call f2() method in object $obj(not new A())
    }
}

$obj = new A();
$obj->f1();
like image 916
Kasynych Avatar asked Dec 29 '25 12:12

Kasynych


1 Answers

You can use a static function

public static function f2{
    echo 'hello!';
}

with f3 defined as

function f3(){
    A::f2();
}

This may not ultimately be the solution you want, however. See more info here.

like image 182
agressen Avatar answered Jan 01 '26 02:01

agressen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!