There is a way to get class properties and convert it using (array)
casting.
$user = (array) get_object_vars($userObject)
But I wonder, I didn't find any direct method to convert array to class properties.
Suppose I have user class with following implementation:
class User
{
private $id = 0;
private $fname = '';
private $lname = '';
private $username = '';
}
I have following array:
$user = array(
'id'=> 2,
'fname' => 'FirstName',
'lname' => 'LastName',
'username' => 'UserName'
);
I am looking for a type cast just like we have (object)
. The issue is (object)
type cast converts array to stdClass
object, but here I want my array to be converted in to my specified class.
The example should be stated like: (my assumption, that PHP should have this. Or it may already have some thing like this and I dont know.)
$userobj = (object User) $user;
And the result of above syntax should be just like:
$userobj->id = $user['id'];
$userobj->fname = $user['fname'];
$userobj->lname = $user['lname'];
$userobj->username = $user['username'];
I want to know if there any direct method, not a logic of mapping. Looking for language level trick.
Note: I am aware of the use of foreach
to get above done. I am looking for some direct method if available in PHP but not get into focus yet (may be!).
Following doesn't solve my question: Convert/cast an stdClass object to another class