Use a variable from __construct() in other methods

2019-06-19 04:53发布

I defined a new variable in __construct() and I want to use it in another function of this class. But my variable is empty in the other function!

this is my code:

class testObject{
     function __construct() {
           global $c;
           $data = array("name"=>$c['name'],
                         "family"=>$c['family']);
     }

     function showInfo() {
           global $data;
           print_r($data);
     }

}

2条回答
戒情不戒烟
2楼-- · 2019-06-19 05:34

You can do this way. Instead of declaring $data as global variable declare as public or private or protected variable inside the class depending on your use. Then set the data inside _construct.

Using global inside a class is not a good method. You can use class properties.

class testObject{
    public $data;

    function __construct() {
        global $c;
        $this->data = array("name"=>$c['name'],
                        "family"=>$c['family']);
    }

    function showInfo() {
        print_r($this->data);
    }

}
查看更多
狗以群分
3楼-- · 2019-06-19 05:44

Declare variable $data as global inside the constructor:

 function __construct() {
       global $c;
       global $data;
       $data = array("name"=>$c['name'],
                     "family"=>$c['family']);
 }

Then, it will be visible in other function as well.

Note that extensive usage of global variables is strongly discouraged, consider redesigning your class to use class variables with getters+setters.

A more proper way would be to use

class testObject
{
     private $data;

     function __construct(array $c) 
     {
         $this->data = array(
             "name"=>$c['name'],
             "family"=>$c['family']
         );
     }

     function showInfo() 
     {
         print_r($this->data);
     }

     // getter: if you need to access data from outside this class
     function getData() 
     {
         return $this->data;
     }
}

Also, consider separating data fields into separate class variables, as follows. Then you have a typical, clean data class.

class testObject
{
     private $name;
     private $family;

     function __construct($name, $family) 
     {
         $this->name = $name;
         $this->family = $family;
     }

     function showInfo() 
     {
         print("name: " . $this->name . ", family: " . $this->family);
     }

     // getters
     function getName() 
     {
         return $this->name;
     }

     function getFamily() 
     {
         return $this->family;
     }

}

And you can even construct this object with data from you global variable $c until you elimitate it from your code:

new testObject($c['name'], $c['family'])
查看更多
登录 后发表回答