php扩展调用php函数,是否可以在PHP字符串中扩展函数调用?

我试着在这样的字符串中调用foo():

echo"This is a ${foo()} car";

function foo() {

return"blue";

}

但是,它最终会出现语法错误。

我在这里发现了一些类似的东西,但并不完全是我需要的:

echo"This is the value of the var named by the return value of getName(): {${getName()}}";

可以这样做吗?

没有一个理由这么做

你需要什么?

为什么不??我认为以下语法非常有用:"My name is $name, and I'm $age years old"。当然,我也可以这样做:"My name is" . $name .", and I'm" . $age ." years old",但是第一个变体看起来更好。我想知道我是否可以对get_name()和get_age()函数做同样的操作。

对于变量,这是可能的,对于函数,这是不可能的。对不起,我不知道为什么。

我觉得看起来不好。事实上,我认为它看起来更糟,因为它需要您从精神上分析变量的字符串。此外,它还具有"I would like to link $foo->$bar"所指含义的模糊含义。那该怎么办?字面上是指$foo . '->' . $bar?江户十一〔六〕号?江户十一〔七〕号?这是我无法忍受的模棱两可。"foo: $foo"看起来可能更干净,但我认为它的可读性要差得多。

有可能吗?不。

Functions, method calls, static class variables, and class constants inside {$} work since

PHP 5. However, the value accessed will be interpreted as the name of a variable in the

scope in which the string is defined. Using single curly braces ({}) will not work for

accessing the return values of functions or methods or the values of class constants or

static class variables.

这是http://www.php.net/manual/en/language.types.string.php language.types.string.parsing.complex上关于卷曲语法的第一个注释。

谢谢,你说服了我!

不是那样的,不是…你可以:

echo"$(" . foo() .");";

不,据我所知,你只能做到:

echo"hello".foo();

function foo() {

return"world";

}

在您的示例中,这将起作用:

$name ="captaintokyo";

echo"This is the value of the var named by the return value of getName(): {${getName()}}";

function getName()

{

return"name";

}

// Output:

// This is the value of the var named by the return value of getName(): captaintokyo

是的,这是可能的。

$func = function($param) { return $param; };

function foo($color) { return"$color car"; }

echo"This is a {$func(foo('blue'))}
";

$title = 'blue car';

echo"This is a {$func(str_replace('blue', 'red', $title))}
";

$func()将作为函数调用,括号中的表达式将作为任何其他PHP代码进行计算。这样就可以直接调用字符串中的几乎任何函数。

这真是一个很好的技巧,不知道它有多有用,因为你需要关闭身份。

您给出的示例:

function foo() {return"hello";}

echo"${foo()}";

这个例子不起作用,因为使用php的{$}格式的函数只允许您以变量名访问结果,然后显示该变量的内容。

在您的示例中,echo语句将尝试回显名为$hello的变量的内容。

要了解它为什么不起作用,我们需要修改示例:

function foo() {return"hello";}

$hello="world";

echo"${foo()}";

此程序将打印world。这似乎就是你在第二个例子中发现的。

如果您希望获得一个程序来打印您的示例中的hello,那么您将无法使用此技术来完成它。然而,好消息是,有很多更简单的方法可以做到这一点。只需返回函数返回值。

将$用单引号括起来,这样它就不会是Me文字,并使用串联来附加foo的值

echo '$' . foo();

function foo() {

return"hello";

}

印刷品:$hello。

你也可以这样做:

echo foo();

$语法类似于shell命令替换,对于php,您可以使用eval,http://php.net/eval

但请注意,Eval是邪恶的…你必须确定你知道你把什么传给埃瓦尔。

这样称呼它:

当你的缺点被我们称为拥有时,你不应该引用Eval的缺点:/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值