【问题标题】:Can I make an alias class name in PHP? [duplicate]我可以在 PHP 中创建一个别名类名吗? [复制]
【发布时间】:2012-01-17 00:13:54
【问题描述】:

可能重复:
Getting static property from a class with dynamic class name in PHP

在阅读我的问题之前先快速浏览一下:

在 PHP 中我们可以:

代码:

<?php
    class Foo
    {
        const TOUCH_ME = 1;
        public function __construct()
        {
        }
    }
    $class = 'Foo';
    $object = new $class();
    $type = $object instanceof Foo;
    echo $type;//Expect to 1
?>

输出:

1

我的问题是,我该怎么做:

代码:

<?php
    class Foo
    {
        const TOUCH_ME = 1;
        public function __construct()
        {
        }
    }
    $class = 'Foo';
    $var = $class::TOUCH_ME;
?>

输出:

一个错误

那么,我该怎么做呢?还是我傻?

【问题讨论】:

  • 升级到 PHP 5.3 或更新版本,$class::TOUCH_ME 工作正常。
  • 如果您只需要常量,则不需要任何复杂的解决方法或 PHP 5.3。一个简单的constant("$class::TOUCH_ME"); 就可以了。

标签: php


【解决方案1】:

自 PHP 5.3 起才有可能,请参阅http://php.net/manual/en/language.oop5.constants.php

【讨论】:

    【解决方案2】:
    php -r ' class Foo { const BAR = 1; } $class = "Foo"; $var = $class::BAR; echo $var; '
    
    // outputs 1
    

    我使用的是 PHP 5.3 版,但我不明白为什么这在早期版本的 PHP 中不起作用,除非它是与后期静态绑定有关的问题:

    http://www.php.net/manual/en/language.oop5.late-static-bindings.php

    【讨论】:

    • codepad.org/a78m2rvq => 你可以访问这个链接。
    • 正如其他人所说,这是您的 PHP 版本的问题。
    猜你喜欢
    • 2017-02-26
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多