Curly braces in string in PHP

后端 未结 5 720
刺人心
刺人心 2020-11-21 23:13

What is the meaning of { } (curly braces) in string literals in PHP?

5条回答
  •  长情又很酷
    2020-11-21 23:46

    I've also found it useful to access object attributes where the attribute names vary by some iterator. For example, I have used the pattern below for a set of time periods: hour, day, month.

    $periods=array('hour', 'day', 'month');
    foreach ($periods as $period)
    {
        $this->{'value_'.$period}=1;
    }
    

    This same pattern can also be used to access class methods. Just build up the method name in the same manner, using strings and string variables.

    You could easily argue to just use an array for the value storage by period. If this application were PHP only, I would agree. I use this pattern when the class attributes map to fields in a database table. While it is possible to store arrays in a database using serialization, it is inefficient, and pointless if the individual fields must be indexed. I often add an array of the field names, keyed by the iterator, for the best of both worlds.

    class timevalues
    {
                                 // Database table values:
        public $value_hour;      // maps to values.value_hour
        public $value_day;       // maps to values.value_day
        public $value_month;     // maps to values.value_month
        public $values=array();
    
        public function __construct()
        {
            $this->value_hour=0;
            $this->value_day=0;
            $this->value_month=0;
            $this->values=array(
                'hour'=>$this->value_hour,
                'day'=>$this->value_day,
                'month'=>$this->value_month,
            );
        }
    }
    

提交回复
热议问题