代码之家  ›  专栏  ›  技术社区  ›  selfsimilar

我可以使用字符串连接在php中定义类const吗?

  •  48
  • selfsimilar  · 技术社区  · 14 年前

    我知道您可以使用字符串连接来创建彼此相关的全局常量:

    define('FOO', 'foo');
    define('BAR', FOO.'bar');  
    echo BAR;
    

    将打印“foobar”。

    但是,尝试使用类常量执行相同操作时出现错误。

    class foobar {
      const foo = 'foo';
      const foo2 = self::foo;
      const bar = self::foo.'bar';
    }
    

    foo2的定义没有问题,但是声明const bar将出错

    分析错误:语法错误,意外的“.”,应为“,”或“;”

    我也试过使用sprintf()这样的函数,但它不喜欢左括号,而喜欢字符串连接符“.”。

    那么,除了像foo2这样的简单的集合情况之外,还有什么方法可以根据彼此来创建类常量呢?

    6 回复  |  直到 8 年前
        1
  •  21
  •   Community CDub    7 年前

    imho,这个问题值得回答 PHP 5.6 + ,感谢@jammin comment

    自php 5.6以来,您可以为常量定义静态标量表达式:

    class Foo { 
      const BAR = "baz";
      const HAZ = self::BAR . " boo\n"; 
    }
    

    虽然这不是问题的一部分,但人们应该意识到执行的局限性。以下内容虽然是静态内容(但可能在运行时被操纵),但无法工作:

    class Foo { 
      public static $bar = "baz";
      const HAZ = self::$bar . " boo\n"; 
    }
    // PHP Parse error:  syntax error, unexpected '$bar' (T_VARIABLE), expecting identifier (T_STRING) or class (T_CLASS)
    
    class Foo { 
      public static function bar () { return "baz";}
      const HAZ = self::bar() . " boo\n"; 
    }
    // PHP Parse error:  syntax error, unexpected '(', expecting ',' or ';'
    

    有关更多信息,请查看: https://wiki.php.net/rfc/const_scalar_exprs http://php.net/manual/en/language.oop5.constants.php

        2
  •  34
  •   user187291    14 年前

    唯一的方法是定义一个表达式,然后在类中使用该常量

    define('foobar', 'foo' . 'bar');
    
    class Foo
    {
        const blah = foobar;
    }
    
    echo Foo::blah;
    

    另一个选择是转到bugs.php.net并请他们修复此问题。

        3
  •  14
  •   Peter Bailey    14 年前

    像这样的事情总是要回到可靠的手册上。

    关于 constants :

    值必须是常量 表达式,而不是(例如) 变量、属性、结果 数学运算或函数 打电话。

    所以……”不”将是答案:d

        4
  •  2
  •   Dumb Guy    14 年前

    对于 常量,除了常量表达式之外,不能指定任何其他内容。引用 PHP manual :

    值必须是常量表达式,而不是(例如)变量、属性、数学运算的结果或函数调用。

        5
  •  1
  •   MuffinTheMan    11 年前

    这可能不是你想要的,但是我遇到了这个问题,所以这里有一个解决方案,我用它来解决我遇到的一个问题(基于@user187291的答案):

    define('app_path', __DIR__ . '/../../');
    const APPLICATION_PATH = app_path;
    .
    .
    .
    require_once(APPLICATION_PATH . "some_directory/some_file.php");
    .
    .
    .
    

    看来效果不错!

        6
  •  0
  •   Bingy    14 年前

    不。

    (我想没有)