Kyle Thomas Kyle Thomas - 1 month ago 15
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:

/products/product-name


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
$state
is false, the required file is the product.php file not the 404.php file.

I have debugged this and the
$state
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?

Also,

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


Does not work, this runs false everytime...

Answer

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

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