简体   繁体   中英

PHP global variable scope inside a class

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.

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 .

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

构造一个新的单例类,用于存储和访问要使用的变量?

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

在课堂上你可以使用$ GLOBALS ['myarray']。

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

    ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM