【问题标题】:PHP Interface class in function arguments函数参数中的 PHP 接口类
【发布时间】:2016-09-18 12:07:59
【问题描述】:

我想像 Java 接口一样使用 PHP 接口。 我如何在 PHP 中完成这项工作?

安卓(Java):

btnDownload.setOnClickListener(new OnClickListener() {          
    @Override
    public void onClick(View v) {
        //---------------------------------
    }
});

我想要在 PHP 中:

$installer->setOnInstallerListener(new IInstaller(){
    function onError()
    {
        echo 'OK';
    }
});

IInstaller 是一个接口:

interface IInstaller
{
    public function onError();
}

【问题讨论】:

    标签: php function class interface listener


    【解决方案1】:

    似乎 PHP7 对此有支持。 http://php.net/manual/en/language.oop5.anonymous.php

    new class(10) extends SomeClass implements SomeInterface {
        private $num;
    
        public function __construct($num)
        {
            $this->num = $num;
        }
    
        use SomeTrait;
    }
    

    使用 PHP5,您可以做的最好的事情就是使用闭包来模仿行为:http://www.clock.co.uk/blog/mimicking-anonymous-classes-in-php-using-closures

    【讨论】:

    • “new class(10)”中的 10 是什么意思?
    • 10 是构造函数值。所以如果你有空的构造函数,你可以把它排除在外
    猜你喜欢
    • 2018-09-15
    • 2012-10-27
    • 2014-08-22
    • 2010-12-09
    • 1970-01-01
    • 2018-11-28
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多