Kyle Thomas Kyle Thomas - 1 year ago 86
PHP Question

Ternary operator - unexpected behavior

I have a Product class which retrieves database data by the product name. The URL would look like this:


My class works fine and retrieves product data when this method is function is executed:

$library->get('Router')->map('GET|POST', '/products/[*:product]', function($prod) use ($library){
require_once(_DIR_ . 'lib/Product.php');
$p = new Product($prod);
$state = $p->prepare();
require_once(_DIR_ . $state ? "views/product.php" : "views/404.php");

Only, when the
is false, the required file is the product.php file not the 404.php file.

I have debugged this and the
IS false when there is no product so my method is returning the correct bool, only, the ternary operator seems to run the TRUE each time.

If I change the expression to this:

require_once(_DIR_ . $state === TRUE ? "views/product.php" : "views/404.php");

It works fine, can someone explain why this is happening? If I was to do:

$example = false;
echo ($example) ? 'yes' : 'no';

It works, so why is it behaving this way?


require_once(_DIR_ . $p->prepare() === TRUE ? "views/product.php" : "views/404.php");

Does not work, this runs false everytime...

Answer Source

Because . has precedence over the ternary operator, you need to use parentheses:

require_once(_DIR_ . ($state ? "views/product.php" : "views/404.php"));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download