Home > Net >  Take value execute class string
Take value execute class string

Time:10-22

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.

CodePudding user response:

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

CodePudding user response:

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];
}
  • Related