douhui5953 2010-05-29 06:39
浏览 31
已采纳

在PHP中初始化静态成员

class Person {
  public static function ShowQualification() {
  }
}

class School {
  public static $Headmaster = new Person(); // NetBeans complains about this line
}

Why is this not possible?

I want to be able to use this like

School::Headmaster::ShowQualification();

..without instantiating any class. How can I do it?

Update: Okay I understood the WHY part. Can someone explain the HOW part? Thanks :)

  • 写回答

2条回答 默认 最新

  • dsaf415212 2010-05-29 06:43
    关注

    From the docs,

    "Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed."

    new Person() is not a literal or a constant, so this won't work.

    You can use a work-around:

    class School {
      public static $Headmaster;
    }
    
    School::$Headmaster = new Person();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

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