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?

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退
  • ¥20 win系统的PYQT程序生成的数据如何放入云服务器阿里云window版?
  • ¥50 invest生境质量模块