views:

148

answers:

3

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 the same class. My current method is this:

<?php

class Log(){

   function Log(){
      $_ENV['access'] = true;
   }

   function test(){
      $access = $ENV['access'];
   }

}

?>

Is there a better way to do this than abusing environment variables? Thanks.

+6  A: 

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 :

Pascal MARTIN
I don't think the () after the class is valid...?
SeanJA
@SeanJA : oh yes, of course, you're right ; I didn't see those when I copy-pasted the code from the OP ;; thanks for your note !
Pascal MARTIN
Ya, I missed it too when I was pasting it into mine...
SeanJA
A: 

You could use the global keyword:

class Log{
    protected $access;
    function Log(){
        global $access;
        $this->access = &$access;
    }
}

But you really should be passing the variable in the constructor:

class Log{
    protected $access;
    function Log($access){
        $this->access = &$access;
    }
    //...Then you have access to the access variable throughout the class:
    function test(){
        echo $this->access;
    }
}
SeanJA
-1 for what? He wanted a global variable.
SeanJA
Log() should be __construct() and both methods miss the public keyword.
Gordon
Unless you want to be compatible with php 4 as well... then it would be log()
SeanJA
yeah, but then you couldnt have the protected keyword ;)
Gordon
And php4 classes have properties as well (though all being public)
VolkerK
It has been quite a while since I used php4, but doesn't the function default to public if there is no keyword? (it does in php 5)
SeanJA
+2  A: 

Globals are considered harmful. If this is an outside dependency, pass it through the constructor and save it inside a property for later use. If you need this to be set only during the call to test, you might want to consider making it an argument to that method.

Gordon
That is what I said with an example, -1 for me!
SeanJA