PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, January 21, 2022

[FIXED] Type Casting of class functions in PHP

 January 21, 2022     casting, php, symfony     No comments   

Issue

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


Solution

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.



Answered By - COil
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing