Access global variable from within a class

前端 未结 4 999
轮回少年
轮回少年 2020-12-04 02:00

I have the following (stripped down) code:



        
相关标签:
4条回答
  • 2020-12-04 02:02

    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.

    0 讨论(0)
  • 2020-12-04 02:07

    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();
    }
    
    0 讨论(0)
  • 2020-12-04 02:10
    <?php
    class A {
        public function Show(){
          return "ciao";
        }
    }
    
    class B {
        function __construct() {
            $a = new A();
            echo $a->Show();
        }
    }
    
    $b = new B();
    ?>
    
    0 讨论(0)
  • 2020-12-04 02:24

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题