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

Categories

0 votes
195 views
in Technique[技术] by (71.8m points)

php - Access global variable from within a class

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

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

1 Answer

0 votes
by (71.8m points)

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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...