duanbai1974
2016-06-26 09:06
浏览 84
已采纳

PHP:魔术方法__toString()的静态变体?

I would like to use PHP's __toString() method in a static manner, like so:

class MyClass {
    public static function __toString() {
        echo 'Hello, I am MyClass!';
    }
}

echo (string) MyClass;

Unfortunately though __toString() cannot be a static method. It would be great if this was possible though, so my question is: Is this something reasonable to propose as a feature request to PHP devs? If not, how can we achieve this kind of functionality as closely to what my example describes as realistically possible?

图片转代码服务由CSDN问答提供 功能建议

我想以静态的方式使用PHP的 __ toString()方法,就像这样 :

  class MyClass {
 public static function __toString(){
 echo'Hello,我是MyClass!'; 
} 
} 
 
echo(  string)MyClass; 
   
 
 

不幸的是, __ toString()不能是静态方法。 如果这是可能的,那将是很好的,所以我的问题是:这是一个合理的建议作为PHP开发人员的功能请求? 如果没有,我们如何能够像我的实例所描述的那样实现这种功能?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzan2740 2016-06-26 09:19
    已采纳

    You can write:

    echo MyClass::class;
    

    Or if you need more control:

    class MyClass
    {
        public static function getClass()
        {
            return get_class();
        }
    }
    
    echo MyClass::getClass();
    

    If you want to have a static class property, you can use this:

    class MyClass {
        static $name = self::class;
    }
    
    echo MyClass::$name;
    

    See also this answer.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题