开发者

Access function in class A from non related class B using object of class A [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Call function of class ONE from class TWO without extend?

why this does not work?

    class A {
        function one() {
            echo "Class A";
        }
    }

    class B {
        function two() {
            echo "C开发者_Go百科lass B";
            $a->one();
        }
    }


    $a = new A; 
    $b = new B;

    $b->two();


This does not work because $a is not a global variable. It should work if you declare $a as global in class B beforehand.

class B {
        function two() {
            global $a;
            echo "Class B";
            $a->one();
        }
    }


As mentioned, this is a variable scope problem. The scope of B::two() does not include the variable $a which has been declared in the global namespace.

The best thing to do is pass $a to B as a dependency. There would be several ways to do this...

For single use in B::two()

public function two(A $a)
{
    echo 'Class B';
    $a->one();
}

Then

$b->two($a);

As a property of B

class B
{
    private $a;

    public function __construct(A $a)
    {
        $this->a = $a;
    }

    public function two()
    {
        echo 'Class B';
        $this->a->one();
    }
}

then

$b = new B($a);
$b->two();


$a is not accessable in Class B in your example. Please read Variable Scope

Try:

class A {
    public function one() {
        echo "Class A";
    }
}

class B {
    public function two() {
        echo "Class B";
        $a = new A;
        $a->one();
    }
}

$b = new B;
$b->two();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜