Search code examples
phparraysobject-properties

I'm not sure if I understand


I'm not sure if I understand properties() method right It's pulling out values from $db_table_fields and making them keys in array $properties and also assigning them as values of the same array...?

don't want just to copy/paste code trying to understand it..

class User{

    protected static $db_table = "users";
    protected static $db_table_fields = array('username','password','first_name','last_name');
    public $id;
    public $username;
    public $password;    
    public $first_name;
    public $last_name;

    protected function properties(){
        $properties = array();
        foreach(self::$db_table_fields as $db_field ){
            if(property_exists($this,$db_field)){
                $properties[$db_field] = $this->$db_field;
            }
        }
        return $properties;
    }

}

Solution

  • It's creating an associative array whose elements correspond to selected properties of the object. The array $db_table_fields lists those properties. It then loops through that array and checks whether $this contains a property with each name. If the property exists, it adds an entry to the $properties array whose key is the property name, and whose value is the property value. This is the critical line:

    $properties[$db_field] = $this->$db_field;
    

    $properties[$db_field] = means to create an element of the $properties array whose key is $db_field (the current element of the loop). And $this->$db_field uses $db_field as a property name to access in the current object.