在php中的child和parents类之间共享的属性 [英] Properties shared between child and parents class in php

查看:188
本文介绍了在php中的child和parents类之间共享的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class parents {
public $ a;
function __construct(){
echo $ this-> a;
}
}
class child extends parents {
function __construct(){
$ this-> a = 1;
parent :: __ construct();
}
}
$ new = new child(); // print 1

上面的代码打印1,这意味着每当我们创建一个子类的实例,并赋值给从它的父继承的属性,它的父类的属性也被赋值。但是下面的代码显示了不同的:

 班上的父母{
public $ a;
function test(){
$ child = new child();
echo $ this-> a;
}
}

class child extends parents {
function __construct(){
$ this-> a = 1;
}
}
$ new = new parents();
$ new-> test(); //不输入任何值



谢谢!



在底部的例子中,你有两个独立的对象独立运行。父对象有$ a,孩子也是这样,但他们不是相同的$ a,因为它们包含在单独的对象中。所以当在父类中打印$ this-> a时,它指的是父的$ a实例,而如果在子类中设置$ this-> a = 1之后回显$ a,它将显示子实例$ a。



希望这为你清除了一些东西。


class parents{
    public $a;
    function __construct(){
        echo $this->a;
    }
}
class child extends parents{
   function __construct(){
        $this->a = 1;
        parent::__construct();
    }
}
$new = new child();//print 1

This code above print 1,which means whenever we create an instance of a child class,and assign value to properties inherited from its parent,the property in its parent class also has been assigned.But the code below shows different:

class parents{
    public $a;
    function test(){
        $child = new child();
        echo $this->a;
    }
}

class child extends parents{
    function __construct(){
        $this->a = 1;
    }
}
$new = new parents();
$new->test();//print nothing

Where I assign value to its child class and the parent apprently didn't have the value it assigned to its child class,why?

Thanks!

解决方案

In the top example, since the construct function is being called from the child class, it is treating the object being used as if it were the child object that is just using a function in the parent class as if it were it's own.

In the bottom example you have two separate objects acting independently. The parent object has it's $a and so does the child, but they are not the same $a since they are contained in separate objects. so when you print $this->a in the parent class, it is referring to the parent's instance of $a whereas if you echo $a after setting $this->a =1 in the child class it would display the child's instance of $a.

Hope this cleared some stuff up for you.

这篇关于在php中的child和parents类之间共享的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆