Outer Variable Access in PHP Class

OrangeRind picture OrangeRind · Jun 23, 2009 · Viewed 11.3k times · Source

Consider the following situation

file: ./include/functions/table-config.php containing:

.
.
$tablePages = 'orweb_pages';
.
.

file: ./include/classes/uri-resolve.php containing:

class URIResolve {
.
.
$category = null ;
.
.
function process_uri() {
...
    $this->category = $tablePages;
...
}
.
.
}

file: ./settings.php containing:

.
.
require_once(ABSPATH.INC.FUNC.'/table-config.php');
require_once(ABSPATH.INC.CLASS.'/uri-resolve.php');
.
.
Will this work. I mean will the access to $tablePages from process_uri() be acceptable or will it give erronous results.

Please suggest corrections or workarounds if error might occur.

Answer

PatrikAkerstrand picture PatrikAkerstrand · Jun 23, 2009

Use the global keyword:

In the file where you're assigning the value.

global $tablePages;
$tablePages = 'orweb_pages';

And in the other file:

class URIResolve {
  var $category;
  function process_uri() {
    global $tablePages;
    $this->category = $tablePages;
  }
}

Also, all global variables are available in the $GLOBALS array (which itself is a superglobal), so you can access the global variable anywhere without using the global keyword by doing something like this:

$my_value = $GLOBALS['tablePages'];

This also serves to make it harder to accidentally overwrite the value of the global. In the former example, any changes you made to $tablePages would change the global variable. Many a security bug has been created by having a global $user and overwriting it with a more powerful user's information.

Another, even safer approach is to provide the variable in the constructor to URIResolve:

class URIResolve {
  var $category;

  function __construct ($tablePages) {
    $this->category= $tablePages;
  }

  function process_uri() {
    // Now you can access table pages here as an variable instance
  }
}

// This would then be used as:
new URIResolve($tablePages);