In PHP: How to call a $variable inside one function that was defined previously inside another function?

后端 未结 2 464
陌清茗
陌清茗 2020-12-05 21:59

I\'m just starting with Object Oriented PHP and I have the following issue:

I have a class that contains a function that contains a certain script. I need to call a

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 22:32

    Make $var a class variable:

    class HelloWorld {
    
        var $var;
    
        function sayHello() {
            echo "Hello";
            $this->var = "World";
        }
    
        function sayWorld() {
            echo $this->var;
        }
    
    }
    

    I would avoid making it a global, unless a lot of other code needs to access it; if it's just something that's to be used within the same class, then that's the perfect candidate for a class member.

    If your sayHello() method was subsequently calling sayWorld(), then an alternative would be to pass the argument to that method.

提交回复
热议问题