PHP traits -定义默认常量[重复]

vojdkbi0  于 2023-02-07  发布在  PHP
关注(0)|答案(1)|浏览(166)
    • 此问题在此处已有答案**:

PHP traits - defining generic constants(7个答案)
5小时前关门了。
基类(通常是抽象类)可以有一些方法,这些方法可以通过覆盖子类中的常量来调整。这些常量也可以有默认值。
示例:

abstract class BaseClass{
    const NAME = '<default name>';

    public function sayHello(){
        printf("Hello! My name is %s\n", static::NAME);
    }
}

// will use default constant value
class SomeClass extends BaseClass{}

// constant value is overridden
class OtherClass extends BaseClass{
    const NAME = 'Stephen Hawking';
}

(new SomeClass())->sayHello(); // Hello! My name is <default name>
(new OtherClass())->sayHello(); // Hello! My name is Stephen Hawking

但是如果我用trait代替abstract class

PHP Fatal error:  Traits cannot have constants in /mnt/tmpfs/1.php on line 4

那么有没有可能把它们用于性状呢?

axr492tv

axr492tv1#

Someone建议改用静态属性,但它不起作用,因为

PHP Fatal error:  OtherClass and SayTrait define the same property ($name) in the composition of OtherClass. However, the definition differs and is considered incompatible. Class was composed in /mnt/tmpfs/1.php on line 19

所以possible workaroud是在父类中使用trait,然后从父类扩展目标类。

trait SayTrait {
    public static $name = '<default name>';

    public function sayHello(){
        printf("Hello! My name is %s\n", static::$name);
    }
}

class SomeClass{
    use SayTrait;
}

// added as workaround.
abstract class ParentClass{
    use SayTrait;
}
// I have to move using trait to parent class to avoid Fatal Error
class OtherClass extends ParentClass {
    public static $name = 'Stephen Hawking';
}

(new SomeClass())->sayHello();
(new OtherClass())->sayHello();

另一个解决方案是如果类常量没有定义,使用方法本身硬编码的值。不幸的是,空合并操作符(??)不适用于常量,所以我不得不使用defined +三元操作符(多亏了https://stackoverflow.com/a/50974262

trait SayTrait {

    public function sayHello(){
        printf("Hello! My name is %s\n", defined('static::NAME')? static::NAME : '<default name>');
    }

}

class SomeClass{
    use SayTrait;
}

class OtherClass {
    use SayTrait;
    const NAME = 'Stephen Hawking';
}

(new SomeClass())->sayHello();
(new OtherClass())->sayHello();

相关问题