doutao8774 2017-07-12 19:29
浏览 222
已采纳

抽象类的属性可以在类外访问吗?

Is is possible to access a variable in a PHP abstract class, i.e.

abstract class Settings
{
    public $application = array
    (
        'Name' => 'MyApp',
        'Version' => '1.0.0',
        'Date' => 'June 1, 2017'
    )
}

echo Settings::application ['Name'];   // doesn't work
  • 写回答

2条回答 默认 最新

  • douti0467 2017-07-12 19:32
    关注

    You could make the variable static, as long as it doesn't need to allow differentiation across instances (i.e. instance variable):

    <?php
    // example code
    
    abstract class Settings
    {
        public static $application = array
        (
            'Name' => 'MyApp',
            'Version' => '1.0.0',
            'Date' => 'June 1, 2017'
        );
    }
    
    echo Settings::$application ['Name'];
    

    Run it in this playground example.

    Though your original access of application was similar to that of a constant. use const to declare a Class constant:

    abstract class Settings
    {
        const application = array
        (
            'Name' => 'MyApp',
            'Version' => '1.0.0',
            'Date' => 'June 1, 2017'
        );
    }
    
    echo Settings::application ['Name'];
    

    Run it in this playground example.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度