PHP - 如何正确使用带变量的大括号?

发布于 2024-12-20 17:03:53 字数 427 浏览 2 评论 0原文

我读了 php 文档,我看到了这个:

    class foo{
        var $bar = 'I am a bar';
    }

    $foo = new foo();
    $identity = 'bar';

    echo "{$foo->$identity}";

我看到有人这样写:

if (!isset($ns->job_{$this->id})){
   //do something
}

但是当我尝试使用这段代码时,它不起作用:

$id1 = 10;

$no = 1;

echo ${id.$no};

你们能告诉我为什么它不起作用以及何时可以将大括号与变量一起使用正确吗?

I read php document and I saw this:

    class foo{
        var $bar = 'I am a bar';
    }

    $foo = new foo();
    $identity = 'bar';

    echo "{$foo->$identity}";

And I saw somebody wrote like this:

if (!isset($ns->job_{$this->id})){
   //do something
}

But when I tried with this code, It didn't work:

$id1 = 10;

$no = 1;

echo ${id.$no};

Can you guys tell me why it didn't work and when I can use braces with variable correctly?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝眸 2024-12-27 17:03:53

实例

括号可用于对象类型,例如,模拟数组索引。假设 $arr 是一个数组类型,$obj 是一个对象,我们有:

$arr['index'] ===
$obj->{'index'}

你可以让它变得更有趣,例如:

$arr["index{$id}"] ===
$obj->{"index{$id}"}

甚至更多:

$arr[count($list)] ===
$obj->{count($list)}

编辑:你的问题 --
变量的变量

// Your problem
$id1 = 10;
$no = 1;
$full = "id{$no}";

var_dump($full); // yeap! $ instead of $ 

Live example

Brackets can be used on object types, for instance, to simulate a array index. Supposing that $arr is an array type and $obj an object, we have:

$arr['index'] ===
$obj->{'index'}

You can make it more fun, for instance:

$arr["index{$id}"] ===
$obj->{"index{$id}"}

Even more:

$arr[count($list)] ===
$obj->{count($list)}

Edit: Your problem --
variable of variable

// Your problem
$id1 = 10;
$no = 1;
$full = "id{$no}";

var_dump($full); // yeap! $ instead of $ 
落在眉间の轻吻 2024-12-27 17:03:53

期待什么?

$id = 10;
$no = 1;
echo "${id}.${no}";  // prints "10.1"

What are you expecting?

$id = 10;
$no = 1;
echo "${id}.${no}";  // prints "10.1"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文