PHP access external $var from within a class function

我是研究僧i 提交于 2019-12-13 03:25:18

问题


In PHP, how do you use an external $var for use within a function in a class? For example, say $some_external_var sets to true and you have something like

class myclass {
bla ....
bla ....

function myfunction()  {

  if (isset($some_external_var)) do something ...

   } 

}


$some_external_var =true;

$obj = new myclass();
$obj->myfunction();

Thanks


回答1:


Global $some_external_var;

function myfunction()  {
  Global $some_external_var;
  if (!empty($some_external_var)) do something ...

   } 

}

But because Global automatically sets it, check if it isn't empty.




回答2:


You'll need to use the global keyword inside your function, to make your external variable visible to that function.

For instance :

$my_var_2 = 'glop';

function test_2()
{
    global $my_var_2;
    var_dump($my_var_2);  // string 'glop' (length=4)
}

test_2();

You could also use the $GLOBALS array, which is always visible, even inside functions.


But it is generally not considered a good practice to use global variables: your classes should not depend on some kind of external stuff that might or might not be there !

A better way would be to pass the variables you need as parameters, either to the methods themselves, or to the constructor of the class...




回答3:


that's bad software design. In order for a class to function, it needs to be provided with data. So, pass that external var into your class, otherwise you're creating unnecessary dependencies.




回答4:


Why don't you just pass this variable during __construct() and make what the object does during construction conditional on the truth value of that variable?




回答5:


Use Setters and Getters or maybe a centralized config like:

function config()
{
  static $data;

  if(!isset($data))
  {
    $data = new stdClass();
  }

  return $data;
}

class myClass
{
    public function myFunction()
    {
        echo "config()->myConfigVar: " . config()->myConfigVar;
    }
}

and the use it:

config()->myConfigVar = "Hello world";

$myClass = new myClass();
$myClass->myFunction();

http://www.evanbot.com/article/universally-accessible-data-php/24



来源:https://stackoverflow.com/questions/1213974/php-access-external-var-from-within-a-class-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!