简体   繁体   English

如何在php中将父类公共变量分配给子类公共变量

[英]how to assign parent class public variable to child class public variable in php

I have created two class, Assigning public class variable to child class variable but not working properly.But the same variable assign working inside function correctly.I didn't get proper reason why like that.Please check below example. 我创建了两个类,将公共类变量分配给子类变量,但不能正常工作。但是同一个变量可以正确地在函数内部工作。我没有得到类似的理由,请检查以下示例。

      <?php
          Class pratice{
            public $a=4;
           }
         Class child extends pratice{
            //public $b =$this->a;//getting error with this assigment
            public function getValue(){
            $this->b = $this->a;//working fine with this
            echo $this->b;
           }
         }
        $obj = new child();
        $obj->getValue();
       ?>

Thanks in advance. 提前致谢。

Well $this refers to an instance of the class, so until you create an instance of the class, $this isn't available. $this指向该类的实例,因此,在创建该类的实例之前, $this不可用。

You would have to do it in the constructor , when it can reference itself in a non-static context. 当它可以在非静态上下文中引用自身时,您将必须在构造函数中执行此操作。

class Child extends Practice
{

    public $b;

    public function __construct()
    {
        $this->b = $this->a;
        echo $this->b;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM