duande3134 2010-12-17 13:28
浏览 53

一个类可以在php中保持静态[重复]

Possible Duplicate:
Is it possible to create static classes in PHP (like in C#)?

Can any one tell me if a php class can be declared as static ?

static class StaticClass
{
    public static function staticMethod()
    {
        return 'foo';
    }
}

This code giving me error.parse error: parse error, expecting `T_VARIABLE'

  • 写回答

3条回答 默认 最新

  • dongpu5874 2010-12-17 13:30
    关注

    No, you can't explicitly declare a PHP class as static.

    You can make its constructor private so attempting to instantiate it (at least from outside the class) causes fatal errors.

    class StaticClass
    {
        private function __construct() {}
    
        public static function staticMethod()
        {
            return 'foo';
        }
    }
    
    // Fatal error: Call to private StaticClass::__construct() from invalid context
    new StaticClass();
    

    If you're looking to implement static initialization and other features found in C# static classes, see the other linked question. Otherwise if all you want is to group some utility methods into a class, simply privatizing the constructor should do the trick.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度