Take value execute class string

cqoc49vn  于 2022-10-22  发布在  PHP
关注(0)|答案(2)|浏览(144)

I have class for take values inside loop as this :
$db_user->take_phone[1];
Inside loop I need take different values for the class

$a=array("phone","name","street");

foreach($a as $aa) {
    echo $db_user->take_'$aa.'[1]
}

As you can see inside the loop I need to change the value inside take_$string , but it doesn't work. I suppose there is a syntax error but I'm not sure. How can I write this to work correctly.
I've tried different ways but haven't found a solution.

j1dl9f46

j1dl9f461#

You can use a variable variable , which takes the form of $var->$property . Notice the extra $ .

$a = array("phone","name","street");

foreach($a as $aa) {
    $var = "take_$aa";
    echo $db_user->$var[1];
}

Demo: https://3v4l.org/HolHZ

qhhrdooz

qhhrdooz2#

You have errors php syntax. I has explained it in my example more:

<?php
$db_user  = new stdClass();
$db_user->take_phone = [
    'p1','p2','p3'
];
$db_user->take_name = [
    'n1','n2','n3'
];

$db_user->take_street = [
    's1','s2','s3'
];  

$a=array("phone","name","street");

foreach($a as $aa) {
    echo $db_user->{'take_'.$aa}[1];
}

相关问题