Access to an external variable in a 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 it work. I mean that access to $ tablePages from process_uri () will be acceptable or give positive results.

Please suggest corrections or workarounds if an error may occur.

+3
source share
3 answers

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

Just turning on

$tablePages = 'orweb_pages';

, . :

define('TABLE_PAGES', 'orweb_pages');

TABLE_PAGES .

, .

+3

:

, .

global $tablePages;
$tablePages = 'orweb_pages';

:

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

, $GLOBALS ( ), , - :

$my_value = $GLOBALS['tablePages'];

. , $tablePages, . $user .

, 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);
+9
<?php
 //Use variable php : $GLOBALS in __construct
 $x = "Example variable outer class";

class ExampleClass{
    public $variables; 
  function __construct()
  {
    $this->variables = $GLOBALS; //get all variables from $GLOBALS
  }
    // example get value var 
  public function UseVar(){
   echo $this->variables['x']; // return Example variable outer class
  }
    // example set value var
  public function setVar(){
    $this->variables['x'] = 100;
  } 
}
echo $x // return Example variable outer class;

$Example = new ExampleClass();
$Example->UseVar(); // return Example variable outer class
$Example->setVar(); // $x = 100;

// or use attr variables 
echo $Example->variables['x']; // 100
$Example->variables['x'] = "Hiii"; 
?>
0
source

Source: https://habr.com/ru/post/1711106/


All Articles