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.
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.
You could use the global keyword:
But you really should be passing the variable in the constructor:
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)
You should take a look at :