Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following (stripped down) code:

<?PHP
    class A {
        function Show(){
            echo "ciao";
        }
    }

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

    class B {
        function __construct() {
            $a->Show();
        }
    }
?>

With a bit of surprise I cannot access the globally defined $a variable from within the class and I get a Undefined variable exception. Any help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
182 views
Welcome To Ask or Share your Answers For Others

1 Answer

please don't use the global method that is being suggested. That makes my stomach hurt.

Pass $a into the constructor of B.

class A {
    function Show(){
            echo "ciao";
    }
}

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

class B {
    function __construct( $a ) {
        $a->Show();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...