PHP global variable scope inside a class

流过昼夜 提交于 2019-12-10 12:46:57

问题


I have the following script

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
  }
}

?>

Is there a way to make $myarray available inside the littleclass, through simple declaration? I don't want to pass it as a parameter to the constructor if that was possible.

Additionally, I hope that you actually CAN make global variables visible to a php class in some manner, but this is my first time facing the problem so I really don't know.


回答1:


include global $myarray at the start of setvalue() function.

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

UPDATE:
As noted in the comments, this is bad practice and should be avoided.
A better solution would be this: https://stackoverflow.com/a/17094513/3407923.




回答2:


in a class you can use any global variable with $GLOBALS['varName'];




回答3:


Construct a new singleton class used to store and access variables you want to use ?




回答4:


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

In the class you just might use $GLOBALS['myarray'].




回答5:


Why dont you just use the getter and setter for this?

<?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 ;
          }    
       }   
    }

    ?>


来源:https://stackoverflow.com/questions/8488407/php-global-variable-scope-inside-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!