When to wrap curly braces around a variable

前端 未结 3 1509
隐瞒了意图╮
隐瞒了意图╮ 2020-12-03 00:51

I don\'t know how to explain this but in simple terms I have seen people using {$variable} when outputting values. I have noticed that {$variable}

3条回答
  •  不思量自难忘°
    2020-12-03 01:21

    A couple of years late but may I add:

    You can even use variable in curly braces to access methods of an Object from a Class dynamically.

    Example:

    $username_method = 'username';
    $realname_method = 'realname';
    
    $username = $user->{$username_method}; // $user->username;
    $name = $user->{$realname_method}; // $user->realname
    

    Not a good example but to demonstrate the functionality.

    Another Example as per @kapreski's request in the comments.

    /**Lets say you need to get some details about the user and store in an 
    array for whatever reason.  
    Make an array of what properties you need to insert. 
    The following would make sense if the properties was massive. Assume it is
    **/
    
    $user = $this->getUser(); //Fetching User object
    
    $userProp = array('uid','username','realname','address','email','age');
    
    $userDetails = array();
    
    foreach($userProp as $key => $property) {
        $userDetails[] =  $user->{$property};       
    }
    
    print_r($userDetails);
    

    Once the loop completes you will see records fetched from user object in your $userDetails array.

    Tested on php 5.6

提交回复
热议问题