symfony - Type Casting of class functions in PHP


I'm using Symfony and Doctrine and I need to compare if an object from JSON has the same attribute than one in the database.

So I've done everything correctly but as I'm new to PHP I can't access the attributes of my object because I don't know how to cast the previous line to a Product.

$oldProduct = new Product();
$oldProduct = $repo->findBy( array('nom' => $product->getNom()));

I tried adding

$oldProduct = Product::$repo->findBy( array('nom' => $product->getNom()));

but that doesn't work

I'm sure it has already been answered but I can't find the keywords to get a similar problem.

Thanks in advance




You can force type casting by adding:

$oldProduct = $repo->findBy(array('nom' => $product->getNom()));
/* @var Product $oldProduct */


$oldProduct = $repo->findBy(array('nom' => $product->getNom()));
if (!$oldProduct instanceof Product) {
    throw new \LogicException('Old product not found.');

The second version is better because it doesn't raise warning for static analyzers.

PS: Note that you can put the block containing the@var comment at the end of the first line instead of having a line for it.

People are also looking for solutions to the problem: php - Multichannels on YouTube with YouTube Analytics API


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.