I've just started using ternary operators as I feel they really do make my code look neater - however today I've encountered a problem.
I am trying to echo some script tags into my header if a certain request variable is set to true (to reduce http requests for un-needed files), however whenever I try to load my page I get an error:
require_once(./public/lib/functions.js'></script>):
^ in the above section, why is the browser interpreting the html encoded character, and why do I lose the <script>
tag which precedes my require statement?
Here is the code I am using.
echo $ajax_required == true
? "<script src='" . require_once(LIBRADIR . 'functions.js') . "'></script>"
: false;
Thanks in advance, Alex.
If its just a .js
file and not a .php
file, then you might have used directly file name as a string, instead require()
.
echo html_entity_decode(($ajax_required == true))
? "<script src='" . LIBRADIR . "functions.js'></script>"
: false;
Note: require() is used to include a .php
script inside code, mostly to just re-use your existing code (functions, classes etc).
Currently it is evaluated as:
require_once(('index.php'). "'></script>")
You just need another parenthesis for higher precedence:
(require_once('index.php'))
^ ^
echo html_entity_decode((true == true))
? "<script src='" . (require_once('index.php')) . "'></script>"
: false;
Also remember require_once
or require
are language construct you don't need to call them as function arguments. You can also write the above statement like this:
(require_once 'index.php')
There is definitely no use of require_once as it is used for PHP files. I think you simply want to do this:
echo $ajax_required? "<script src='" . LIBRADIR . "functions.js'></script>": "";
This will just print the output that comes from the ternary operator i.e. either the script tag or empty string.