douchiwan1503 2019-08-01 18:42
浏览 260

PHP特征 - 定义默认常量

Base classes(usually abstact ones) can have methods which can be tuned with overriding constants in child classes. Those contants can also have default values.

example:

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

    public function sayHello(){
        printf("Hello! My name is %s
", 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

But if I replace abstact class with trait I get

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

So is it possible to use them in traits?

  • 写回答

1条回答 默认 最新

  • du4373 2019-08-01 18:42
    关注

    Someone suggested to use static properties instead, but it doesn't work because of

    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
    

    So possible workaroud is to use trait in parent class then extend target class from it.

    trait SayTrait {
        public static $name = '<default name>';
    
        public function sayHello(){
            printf("Hello! My name is %s
    ", 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();
    
    

    Another solution is to use value hardcoded in method itself if class constant is not defined. Unfortunately, null coalescing operator (??) doesn't work with constants so I have to use defined + ternary operator(thanks to https://stackoverflow.com/a/50974262)

    trait SayTrait {
    
        public function sayHello(){
            printf("Hello! My name is %s
    ", 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();
    
    
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题