Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 771
roamcel Avatar asked Dec 13 '11 11:12

roamcel


People also ask

Can global variable used inside a class?

Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.

Do global variables have scope?

A global variable has Global Scope: All scripts and functions on a web page can access it.

How can use global variable inside class in PHP?

Accessing global variable inside function: The ways to access the global variable inside functions are: Using global keyword. Using array GLOBALS[var_name]: It stores all global variables in an array called $GLOBALS[var_name]. Var_name is the name of the variable.

What does $globals mean in PHP?

$GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.


1 Answers

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.

like image 189
Nick Shvelidze Avatar answered Oct 13 '22 00:10

Nick Shvelidze