PHP - Access Object Attributes Dynamically

I want to access object attributes with child objects dynamically just by specifying the attribute in a string variable. 

$book->category->name


$attr="category->name";
$book=\App\Models\Book::find(2);
echo $book->$attr;

Result : null

Solution :

$attr="category->name";
$book=\App\Models\Book::find(2);
$parts=explode("->",$attr);
$h=$book;
foreach($parts as $p){
    $h=$h->$p;
}
echo $h;

Result : book category name



0 comments:

 
Copyright © peyotest