pistacchio
pistacchio

Reputation: 58863

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?

Upvotes: 12

Views: 31477

Answers (4)

Jay Zeng
Jay Zeng

Reputation: 1421

<?php
class A {
    public function Show(){
      return "ciao";
    }
}

class B {
    function __construct() {
        $a = new A();
        echo $a->Show();
    }
}

$b = new B();
?>

Upvotes: -1

Galen
Galen

Reputation: 30170

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

Upvotes: 18

Franz
Franz

Reputation: 11553

Why the surprise? That's a pretty logical variable scope problem there...

I suggest you use either the global keyword or the variable $GLOBALS to access your variable.

EDIT: So, in your case that will be:

global $a;
$a->Show();

or

$GLOBALS['a']->Show();

EDIT 2: And, since Vinko is right, I suggest you take a look at PHP's manual about variable scope.

Upvotes: 13

LiraNuna
LiraNuna

Reputation: 67232

You will need to define it as a global variable inside the scope of the function you want to use it at.

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

Upvotes: 8

Related Questions