Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php类扩展器和父级';s构造器_Php_Class_Constructor - Fatal编程技术网

php类扩展器和父级';s构造器

php类扩展器和父级';s构造器,php,class,constructor,Php,Class,Constructor,我有一节课 class parent { function __construct(){ global $var; } } 班级家长{ 函数_u构造(){ 全球$var; } } 还有一节课 class child extends parent { function construct(){ parent :: __construct; } function print(){ echo $var; } } 类子级扩展父级{ 函数构造(){ 父项::_构造; } 函数打印(){ echo$var;

我有一节课

class parent { function __construct(){ global $var; } } 班级家长{ 函数_u构造(){ 全球$var; } } 还有一节课

class child extends parent { function construct(){ parent :: __construct; } function print(){ echo $var; } } 类子级扩展父级{ 函数构造(){ 父项::_构造; } 函数打印(){ echo$var; } } $a=新生儿; $a->print(); 有没有办法使print()方法可以使用$var而不调用
global$var内部
打印()


谢谢

不,这是不可能的,因为它只是一个全局变量,因此在父类或继承类中没有任何特殊状态

但是,您可以:

  • 将父类中的实例(即:类级别)变量设置为与全局变量相同的值。然后在子类print方法中使用继承的变量

  • 将全局变量作为参数传递到构造函数中。但是,您需要同时修改子构造函数(将变量传递给父构造函数)和父构造函数


  • 如果将$var定义为成员变量,那么这是可行的

    class parent {
      public $var;
      function __construct(){
        global $var;
        $this->var = $var;
      }
    }
    
    class child extends parent {
      function construct(){
        parent :: __construct;
      }
      function print(){
        echo $this->var;
      }
    }
    
    $a = new child;
    $a->print();
    
    你的代码错了。(您需要在print方法中使用
    echo$this->var;
    ):-)
    class parent {
      public $var;
      function __construct(){
        global $var;
        $this->var = $var;
      }
    }
    
    class child extends parent {
      function construct(){
        parent :: __construct;
      }
      function print(){
        echo $this->var;
      }
    }
    
    $a = new child;
    $a->print();