Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outer Variable Access in PHP Class

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.


2 Answers

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);
like image 118
3 revs, 2 users 74%PatrikAkerstrand Avatar answered Aug 15 '26 19:08

3 revs, 2 users 74%PatrikAkerstrand


Use a global (not recommended), a constant or a singleton configuration class.

Simply including

$tablePages = 'orweb_pages';

will give your variable local scope so it won't be visible inside other classes. If you use a constant:

define('TABLE_PAGES', 'orweb_pages');

TABLE_PAGES will be available for read access throughout the application regardless of scope.

The advantage of a constant over a global variable is that you dont have to worry about it being overridden in other areas of the application.

like image 20
fnl Avatar answered Aug 15 '26 20:08

fnl