为什么PHP私有变量在扩展类上起作用? [英] Why is PHP private variables working on extended class?

查看:49
本文介绍了为什么PHP私有变量在扩展类上起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试从扩展类而不是基类中设置属性的值时,它是否会生成错误?

Shouldn't it generate error when i try to set the value of a property from the extended class instead of a base class?

<?php
class first{
    public $id = 22;
    private $name;
    protected $email;
    public function __construct(){
        echo "Base function constructor<br />";
    }
    public function printit(){
        echo "Hello World<br />";
    }
    public function __destruct(){
        echo "Base function destructor!<br />";
    }
}
class second extends first{
    public function __construct($myName, $myEmail){
        $this->name = $myName;
        $this->email = $myEmail;
        $this->reveal();
    }
    public function reveal(){
        echo $this->name.'<br />';
        echo $this->email.'<br />';
    }
}
$object = new second('sth','aaa@bbb.com');

?>

推荐答案

私有变量在子类中不可访问.这就是访问修饰符 protected 的用途.发生的事情是,当您访问一个不存在的变量时,它将使用默认的访问修饰符 public 为您创建一个变量.

Private variables are not accessible in subclasses. Thats what the access modifier protected is for. What happened here is that when you access a variable that doesn't exist, it creates one for you with the default access modifier of public.

这是向您显示状态的UML:

Here is the UML to show you the state:

请注意:子类仍然可以访问其父类中的所有 public protected 方法和变量-但不在UML图中!

Please note: the subclass still has access to all the public and protected methods and variables from its superclass - but are not in the UML diagram!

这篇关于为什么PHP私有变量在扩展类上起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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