在类构造函数外部赋值变量以供类内部使用


Assigning variables outside the class constructor for use inside the class?

我刚刚开始使用类构造函数。在下面的脚本中,我想从类外部传入$arg2值。

我需要如何定义一个变量$someVariable=n,以便它可以从父文件的类构造函数外部设置,其中包括下面的文件?

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();
    }

就像这样使用,但不建议这样使用

$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
演示工作

你不能使用一些'外部'变量来设置参数$arg2的默认值。默认值(逻辑上)在函数的"定义时间"设置。因此,这些参数需要是文字(常量)值。

因此,这些都是很好的声明:
   function makecoffee($type = "cappuccino") { }
   function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL) { } 

如果你想"注入"外部的东西,你需要这样做:

$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

注意,在PHP中访问全局变量是坏风格(就像在任何其他面向对象语言中一样)。