如何让 PHP 在双引号中评估静态变量?
我想做这样的事情:
log("self::$CLASS $METHOD entering");
我已经尝试了各种{}
组合来获取 的变量值self::$CLASS
,但没有任何效果。我目前已经解决了字符串连接问题,但输入起来很痛苦:
log(self::$CLASS . " $METHOD entering");
对不起,你不能那样做。它只适用于简单的表达式。见这里。
不幸的是,目前还没有办法做到这一点。此处答案之一中的示例将不起作用,因为{${self::$CLASS}}
不会返回 的内容self::$CLASS
,但会返回名称为 in 的变量的内容self::$CLASS
。
这是一个示例,它不返回myvar
,但是aaa
:
$myvar = 'aaa';
self::$CLASS = 'myvar';
echo "{${self::$CLASS}}";
使用存储在变量中的匿名标识函数。这样,您将$
立即拥有{
:
$I = function($v) { return $v; };
$interpolated = "Doing {$I(self::FOO)} with {$I(self::BAR)}";
(我在这个例子中使用了类常量,但这也适用于静态变量)。
我不知道您的问题的答案,但您可以使用__METHOD__
魔术常量显示类名和方法。
<?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();
我知道这是一个老问题,但我觉得奇怪的是[sprintf][1]
还没有人建议这个功能。
说:
<?php
class Foo {
public static $a = 'apple';
}
你会用它:
echo sprintf( '$a value is %s', Foo::$a );
所以在你的例子中:
log(
sprintf ( ' %s $METHOD entering', self::$CLASS )
);
//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)";
只需使用串联即可。 您会惊讶于字符串中的变量插值是多么低效。
虽然这可能属于预优化或微优化的范畴,但我认为您在这个示例中实际上并没有获得任何优雅。
就个人而言,如果我要对其中一个进行微小的优化,并且我的选择是“更快”和“更容易输入” - 我会选择“更快”。因为您只输入了几次,但它可能会执行数千次。
是的,可以这样做:
log("{${self::$CLASS}} $METHOD entering");