Doctor Who Doctor Who - 2 months ago 9
PHP Question

How to get object from ArrayObgect in php?

i have problem !
I had just started working with php , but i understand all , but one thing i try understand , but can't...(
So the problem is this - I create a class, for example, this:

class User{
public $name;
public $password;

public function getPassword()
{
return $this->password;
}

public function getName()
{
return $this->name;
}
}


When I try to create an array of objects of this class, pre-filled with data objects:

{
$arrayUsers = new ArrayObject();

$user1 = new User();
$user1->name="lol";
$user1->password=9898898;

$user2 = new User();
$user2->name="lal";
$user2->password=988;


$user3 = new User();
$user3->name="lRus";
$user3->password=1;


$arrayUsers->append(array($user1,$user2,$user3));
}


And after trying to get the object (User class) back from the array, then it does not work ... (Tried many ways, just tried array class)
So I have two questions:
1. How to get out of this array is the object class user?
1.1 In this case, the object functions continue to operate. For example :

$obtainedObject_parentClass_is_User->getName();
//Log : "lol"


2. If the answer to the previous question is not possible, then how to implement an array where you can get the object, after which you can use?
For example like this:

$obtainedObject_parentClass_is_User->getName();
//Log : "lol"

Answer

I think you may be confused between the PHP class ArrayObject and an array of objects.

You can declare your array of objects in one statement like,

$users = [
    'user_1' => new User(),
    'user_2' => new User(),
    'user_3' => new User()
];

You can then assign the properties like,

$users['user_1']->name = 'Barry';
$users['user_1']->password = 'superSecret';
/// etc...

Then to retreive the data,

echo $users['user_1']->getName(); // returns Barry
Comments