为什么不能从PHP中的抽象类调用抽象函数? [英] Why can't you call abstract functions from abstract classes in PHP?

查看:113
本文介绍了为什么不能从PHP中的抽象类调用抽象函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个抽象的父类,以及一个扩展它的具体类.为什么父类不能调用抽象函数?

I've set up an abstract parent class, and a concrete class which extends it. Why can the parent class not call the abstract function?

//foo.php
<?php
    abstract class AbstractFoo{
        abstract public static function foo();
        public static function getFoo(){
            return self::foo();//line 5
        }
    }

    class ConcreteFoo extends AbstractFoo{
        public static function foo(){
            return "bar";
        }
    }

    echo ConcreteFoo::getFoo();
?>

错误:

致命错误:无法在第5行的 foo.php 中调用抽象方法AbstractFoo :: foo()

Fatal error: Cannot call abstract method AbstractFoo::foo() in foo.php on line 5

推荐答案

这是正确的实现;您应该使用静态而不是自我,以便使用添加静态绑定:

This is a correct implementation; you should use static, not self, in order to use late static bindings:

abstract class AbstractFoo{
    public static function foo() {
        throw new RuntimeException("Unimplemented");
    }
    public static function getFoo(){
        return static::foo();
    }
}

class ConcreteFoo extends AbstractFoo{
    public static function foo(){
        return "bar";
    }
}

echo ConcreteFoo::getFoo();

给出了预期的小节".

请注意,这并不是真正的多态性.静态键控只是解析为从中调用静态方法的类.如果声明抽象静态方法,则会收到严格警告.如果子级(子级)中不存在所有静态方法,PHP只会从它们中复制所有静态方法.

Note that this is not really polymorphism. The static keywork is just resolved into the class from which the static method was called. If you declare an abstract static method, you will receive a strict warning. PHP just copies all static methods from the parent (super) class if they do not exist in the child (sub) class.

这篇关于为什么不能从PHP中的抽象类调用抽象函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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