php 调用父类变量,PHP-通过实例化父类访问常量

首先输入一些代码…

FlashBagUtil类包含常量:

class FlashBagUtil

{

const TYPE_NOTICE = 'notice';

const TYPE_WARNING = 'warning';

const TYPE_ALERT = 'alert';

const LANG_EN = 'en';

const LANG_RU = 'ru';

const LANG_IL = 'il';

}

家长班:

class CoreController

{

public $flashUtil;

public function __construct()

{

$this->flashUtil = new FlashBagUtil;

}

}

子班:

class BatchController extends CoreController

{

public function indexAction()

{

// Method 1 - This works fine

$flash = $this->flashUtil;

$flashType = $flash::TYPE_NOTICE;

// Method 2 - This, obviously, does not

$flashType = $this->flashUtil::TYPE_NOTICE;

// Method 3 - Neither does this as $flashUtil is a non-static instantiated object

$flashType = self::$flashUtil::TYPE_NOTICE;

}

}

PHP文档states:不能使用实例化的类对象访问声明为static的属性(尽管可以使用static方法).

但是我似乎能够用第一种方法做到这一点.我想念什么?

在这种情况下,方法1是访问静态内容的唯一,最干净的方法吗?

解决方法:

您所引用的类constant与类变量(属性)不同,并且可被实例化对象访问.您正在引用的文档引用了用static关键字(即private static $flashUtil;)定义的类变量,如果您习惯于使用其他更严格类型的OOP语言进行编程,则可能会引起混淆.

标签:oop,php

来源: https://codeday.me/bug/20191121/2050672.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值