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

查看:29
本文介绍了为什么不能从 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天全站免登陆