JiggyJinjo
JiggyJinjo

Reputation: 197

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()));
$oldProduct->

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

Upvotes: 2

Views: 1827

Answers (1)

COil
COil

Reputation: 7596

You can force type casting by adding:

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

Or:

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

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.

Upvotes: 4

Related Questions