PHP继承,使用子变量的父函数 [英] PHP inheritance, parent functions using child variables

查看:82
本文介绍了PHP继承,使用子变量的父函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在审查一些PHP代码时,我发现了一件奇怪的事情.这是它的简单示例说明:

While reviewing some PHP code I've discovered a strange thing. Here is the simple example illustration of it:

文件A.php:

<?php
class A{
    public function methodA(){
        echo $this->B;
    }
}
?>

文件B.php:

<?php
    class B extends A{
        public $B = "It's working!";
    }
?>

文件test.php:

File test.php:

<?php
    require_once("A.php");
    require_once("B.php");
    $b = new B();
    $b->methodA();
?>

正在运行的test.php输出正在运行!",但问题是为什么它在运行? :)这是功能还是错误?类A中的方法methodA也可以调用类B中的方法,这些方法在OOP中不起作用.

Running test.php prints out "It's working!", but question is why is it working? :) Is this a feature or a bug? Method methodA in class A can also call methods that are in class B which should not work in OOP.

推荐答案

您仅实例化类B.暂时忽略A,并假装methodA()是类B的一部分.

You're only instantiating class B. Ignore A for the moment, and pretend that methodA() is part of class B.

当类B扩展A时,它将获得A的所有功能.在代码运行之前(而不是在之前),不会评估$this->B.因此,不会发生错误,并且不会发生,因为类B中的$this->B存在.

When class B extends A, it gets all of A's functions. $this->B isn't evaluated until the code is running, not prior. Therefore no error occurs, and won't occur as $this->B exists in class B.

这篇关于PHP继承,使用子变量的父函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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