简体   繁体   中英

(Symfony3/php7) Cannot use object of type AppBundle\Entity as array

I have an error: " Cannot use object of type AppBundle\\Entity as array ", and it makes no sense for me, imo it's okay.

if ($form->isSubmitted() && $form->isValid()) {
            $user = $form->getData();
            $repository = $this->getDoctrine()->getRepository(User::class);
            $findUser = $repository->findOneBy(['username' => $form->getData()['username']]);
            if ($findUser) {
                return $this->redirectToRoute('login');
            }

Error Cannot use object of type AppBundle\\Entity\\User as array is at line with " $findUser = "

Can someone explain my why isn't it working?

Symfony 3.3, PHP 7

This example here explains everything:

$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    // $form->getData() holds the submitted values
    // but, the original `$task` variable has also been updated
    $task = $form->getData();

    ...
}

Thus, $form->getData() holds the entity. So, if your User entity has a username attribute, you should call it as $form->getData()->getUsername() or whatever getter you have there.

Usualy when you get error like this you have to check data type. If variable is array you can access it only as array using $variable['index']; , if it is object you can access it using $variable->index; . Best way to figure out variable type is to use print_r($variable); or var_dump($variable); and it will output variable type for you. In your case you will use print_r($form->getData()); or var_dump($form->getData()); . If you use wrong way to get data from variable (array/object) you will receive (Cannot use object of type) error.

If it is array (in your case it isn't):

$form->getData()['username'];

If it is object:

$form->getData()->username;

if your framework has getters and setters:

$form->getData()->getUsername();

It seems you doesn't see differences between objects and arrays. Let's say you have an object (class) Car and that object has a property eg type set to 'Van'. Now you want to get this type. How you do it? Using -> symbol.

$car = new Car();
echo $car->type; //Van

Now we have an array $car with named index type set to Muscle .

$car = ['type' => 'Muscle'];
echo $car['type']; //Muscle

You cannot treat Object as Array and vice versa. You have Entity (which is just a class, object) so you have to treat it like an object.

So if you have Entity User you access its properties using -> not [] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM