类内的PHP全局变量作用域


PHP global variable scope inside a class

我有以下脚本

myclass.php

<?php
$myarray = array('firstval','secondval');
class littleclass {
  private $myvalue;
  public function __construct() {
    $myvalue = "INIT!";
  }
  public function setvalue() {
    $myvalue = $myarray[0];   //ERROR: $myarray does not exist inside the class
  }
}
?>

是否有一种方法,使$myarray内可用的小类,通过简单的声明?如果可能的话,我不想把它作为参数传递给构造函数。

另外,我希望你实际上可以使全局变量以某种方式对php类可见,但这是我第一次面对这个问题,所以我真的不知道。

setvalue()函数开始时包含global $myarray

public function setvalue() {
    global $myarray;
    $myvalue = $myarray[0];
}

更新:
正如评论中所指出的,这是不好的做法,应该避免。
更好的解决方案是:https://stackoverflow.com/a/17094513/3407923.

在类中可以使用任何全局变量$GLOBALS['varName'];

构造一个新的单例类来存储和访问你想要使用的变量

 $GLOBALS['myarray'] =  array('firstval','secondval');

在类中,您可以使用$GLOBALS['myarray']。

为什么不直接使用getter和setter呢?

<?php
    $oLittleclass = new littleclass ;
    $oLittleclass->myarray =  array('firstval','secondval');
    echo "firstval: " . $oLittleclass->firstval . " secondval: " . $oLittleclass->secondval ;
    class littleclass 
    {
      private $myvalue ;
      private $aMyarray ;
      public function __construct() {
        $myvalue = "INIT!";
      }
      public function __set( $key, $value )
      {
        switch( $key )
        {
          case "myarray" :
            $this->aMyarray = $value ;
          break ;
        }
      }
       public function __get( $key )
       {
          switch( $key )
          {
            case "firstval" :
              return $this->aMyarray[0] ;
            break ;
            case "secondval" :
              return $this->aMyarray[1] ;
            break ;
          }    
       }   
    }
    ?>