简体   繁体   English

如何在PHP 7.x中强制转换匿名类?

[英]How to cast an anonymous class in PHP 7.x?

I wondered if there was a way to type the return of a method that instantiates an anonymous class? 我想知道是否有一种方法可以键入实例化匿名类的方法的返回值?

php 的PHP

public function getApi() // <-- type ?
{
    $api = $this->api ?: [];
    return new class ($api)
    {
        private $key, $validTill;
        public function __construct(array $api)
        {
            $this->key       = array_key_exists('key', $api) ? $api['key'] : null;
            $this->validTill = array_key_exists('validTill', $api) ? $api['validTill'] : null;
        }
        public function getKey():?string
        {
            return $this->key;
        }
        public function getValidTill(): ?string
        {
            return $this->validTill;
        }
    };
}

If you're concerned about the type, or behavior, of the returned class, you really should define an interface for this: 如果您担心返回的类的类型或行为,则确实应该为此定义一个接口:

interface KeyInterface 
{
    public function getKey(): ?string;
    public function getValidTill(): ?string;
}

Then have the anonymous class implement the interface: 然后让匿名类实现接口:

public function getApi(): KeyInterface
{
    $api = $this->api ?: [];
    return new class ($api) implements KeyInterface
    ...
}

Anonymous classes can still implement interfaces and inherit from other classes. 匿名类仍然可以实现接口并从其他类继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM