dongshan1036 2014-07-04 08:51
浏览 76

将常量赋给最终类并调用其常量

I have the following code and I am using php 5.5.6

product.php

class product {

    const STATUS = status;

    function __construct(){}

    public function printStatus($status){
        echo $status;
    }
}

final class status {
    const BROKEN = "br";
    const AVAILABLE = "av";
}

index.php

include("product.php");

$pr = new product();
$st = product::STATUS;
$pr->printStatus($st::BROKEN);

The above code gives as an output br, which is the expected

index2.php

include("product.php");

$pr = new product();
$pr->printStatus(product::STATUS::BROKEN);

The above code gives the following error Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM) in ... which means that line $pr->printStatus(product::STATUS::BROKEN);

Does anyone know why this is happening? Is there a php limitation?

  • 写回答

1条回答 默认 最新

  • dsjq62428 2014-07-04 09:04
    关注

    The following code is wrong:

    $pr->printStatus(product::STATUS::BROKEN);
    

    You can't set a constant at runtime. Maybe it would be better you're using a variable in class product like:

    public $STATUS = status::AVAILABLE;
    

    Then you can do something like this:

    <?php
    include("product.php");
    
    $pr = new product();
    $pr->STATUS = status::BROKEN;
    $pr->printStatus($pr->STATUS);
    ?>
    

    With that you can set the STATUS of a product object whenever you want.

    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大