Global variable inside a constructor with PHP

前端 未结 3 1520
情话喂你
情话喂你 2021-01-18 10:50

This should be obvious, but I\'m getting a bit confused about PHP variable scope.

I have a variable inside a Constructor, which I want to use later in a function in

3条回答
  •  悲&欢浪女
    2021-01-18 11:12

    You could use a class variable, which has a context of... a class :
    (Example for PHP 5, of course ; I've re-written a few things so your code is more PHP5-compliant)

    class Log {
       // Declaration of the propery
       protected $_myVar;
    
       public function __construct() {
          // The property is accessed via $this->nameOfTheProperty :
          $this->_myVar = true;
       }
    
       public function test() {
          // Once the property has been set in the constructor, it keeps its value for the whole object :
          $access = $this->_myVar;
       }
    
    }
    

    You should take a look at :

    • The "Classes and Objects" section of the PHP manual
    • And, for this specific question, the sub-section Properties

提交回复
热议问题