I'm just beginning to work with class constructors. In the script below, I want to pass in the $arg2 value from outside the class.
How do I need to define a variable $someVariable=n, so that it can be set from outside the class constructor from the parent file which includes the file below?
class myClassTest
{
public $var1;
public $var2;
public $var3;
function __construct($arg1,$arg2=$someVariable){ //MAKE $arg2 dynamically set from outside the class
$this->var1 = $arg1;
$this->var2 = $arg2;
$this->var3 = array();
}
Just use it like this, however it's not recommended
$someGlobalVar = "test";
class myClassTest
{
public $var1;
public $var2;
public $var3;
function __construct($arg1,$arg2=null){
if ($arg2 === null){
global $someGlobalVar;
$arg2 = $someGlobalVar;
}
echo $arg2;
$this->var1 = $arg1;
$this->var2 = $arg2;
$this->var3 = array();
}
}
$class = new myClassTest('something'); //outputs test
You can't set the default value of argument $arg2 using some 'external' variable. Default values get (logically) set at 'definition time' of the function. Thus, these parameters needs to be literal (constant) values.
Thus, these are fine declarations:
function makecoffee($type = "cappuccino") { }
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL) { }
If you want to 'inject' external stuff, you need to do something like this:
$someglobalVariable = 'whatever';
class myClassTest
{
public $var1;
public $var2;
public $var3;
function __construct($arg1,$arg2=null){ //MAKE $numres dynamic from outside the class
global $someglobalVariable;
if ( ! isset( $arg2 ) ) {
$this->var2 = $someglobalVariable;
} else {
$this->var2 = $arg2;
}
$this->var1 = $arg1;
$this->var3 = array();
}
} // end of class
Note, that it is bad style to access global variables in PHP (as in any other object-oriented language).