40

如何让 PHP 在双引号中评估静态变量?

我想做这样的事情:

log("self::$CLASS $METHOD entering");

我已经尝试了各种{}组合来获取 的变量值self::$CLASS,但没有任何效果。我目前已经解决了字符串连接问题,但输入起来很痛苦:

log(self::$CLASS . " $METHOD entering");
4

9 回答 9

38

对不起,你不能那样做。它只适用于简单的表达式。见这里

于 2009-08-12T16:11:19.950 回答
6

不幸的是,目前还没有办法做到这一点。此处答案之一中的示例将不起作用,因为{${self::$CLASS}}不会返回 的内容self::$CLASS,但会返回名称为 in 的变量的内容self::$CLASS

这是一个示例,它不返回myvar,但是aaa

$myvar = 'aaa';
self::$CLASS = 'myvar';
echo "{${self::$CLASS}}";
于 2013-09-24T14:24:46.130 回答
5

使用存储在变量中的匿名标识函数。这样,您将$立即拥有{

$I = function($v) { return $v; }; $interpolated = "Doing {$I(self::FOO)} with {$I(self::BAR)}";

(我在这个例子中使用了类常量,但这也适用于静态变量)。

于 2018-05-27T16:40:56.670 回答
4

我不知道您的问题的答案,但您可以使用__METHOD__ 魔术常量显示类名和方法。

于 2009-08-12T15:56:49.840 回答
1
<?php

class test {
    public $static = 'text';
    public $self = __CLASS__;
    // static Method
    static function author() {
        return "Frank Glück";
    }
    // static variable
    static $url = 'https://www.dozent.net';
    public function dothis() {
       $self = __CLASS__;
       echo <<<TEST
           
           {${!${''}=static::author()}} // works
           {$self::author()}            // works
           {$this->self::author()}      // works
           ${!${''}=self::author()}     // works
           
           {${$this->self}}::author()}} // don't works
           ${${self::author()}}         // do/don't works but with notice
           ${@${self::author()}}        // works but with @ !
           
TEST;
    }
}

$test = 'test'; // this is the trick, put the Classname into a variable

echo "{$test::author()} {$$test::$url}";
echo <<<HTML
<div>{$test::author()}</div>
<div>{$$test::$url}</div>
HTML;

$test = new test();
$test->dothis();
于 2020-11-12T08:43:00.160 回答
0

我知道这是一个老问题,但我觉得奇怪的是[sprintf][1]还没有人建议这个功能。

说:

<?php

class Foo {

    public static $a = 'apple';

}

你会用它:

echo sprintf( '$a value is %s', Foo::$a );

所以在你的例子中:

log(
    sprintf ( ' %s $METHOD entering', self::$CLASS )
);
于 2018-09-30T18:49:35.573 回答
0
//define below
function EXPR($v) { return $v; }
$E = EXPR;

//now you can use it in string
echo "hello - three is equal to $E(1+2)";
于 2020-07-21T11:31:39.590 回答
-2

只需使用串联即可。 您会惊讶于字符串中的变量插值是多么低效

虽然这可能属于预优化或微优化的范畴,但我认为您在这个示例中实际上并没有获得任何优雅。

就个人而言,如果我要对其中一个进行微小的优化,并且我的选择是“更快”和“更容易输入” - 我会选择“更快”。因为您只输入了几次,但它可能会执行数千次。

于 2009-08-12T16:19:12.837 回答
-5

是的,可以这样做:

log("{${self::$CLASS}} $METHOD entering");
于 2013-08-12T14:47:07.940 回答