18

I have the following code

define("SCRIPT_URL", "");
function ifScriptFolder() {
    if(isset(SCRIPT_URL) && !empty(SCRIPT_URL)) {
        echo "/".SCRIPT_URL."/";
    } else {
        echo "/";
    }
}

but it's giving me the following error:

Parse error: syntax error, unexpected ')', expecting :: (T_PAAMAYIM_NEKUDOTAYIM) in *(path)* on line 3

Can anyone see what's going wrong here or how to fix it?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
dpDesignz
  • 1,909
  • 10
  • 34
  • 70

3 Answers3

13

If you trying to determine if constant exists, then try to use defined() or constant(), not isset().


From php.net:

Function defined():

Returns TRUE if the named constant given by name has been defined, FALSE otherwise.

Function constant():

Returns the value of the constant, or NULL if the constant is not defined.


Fixed function:

function ifScriptFolder() {
    echo defined('SCRIPT_URL') ? "/" . constant('SCRIPT_URL') . "/" : "/"
}

UPD:

The defined() function is a better solution for this, because it will not emit E_WARNING if constant was not defined.

BlitZ
  • 12,038
  • 3
  • 49
  • 68
  • Agreed that the functions should be used. However, the question is about a parse or compilation error i.e. the script does not even run so how can these functions be of help? – ericn Oct 04 '13 at 07:11
  • @fuzzybee This question about misuse and misunderstanig of use `isset()` for constant. And as the result - parse error. – BlitZ Oct 04 '13 at 07:27
5

PHP constants are not variables, so you don't use isset or empty to check them.

Instead, you can use defined:

defined('SCRIPT_URL')

to return a boolean if the field as been defined, then if it is, do a standard comparison on the value to check if it is truthy.

It's also worth noting (for future reference) that isset is not a regular function; it is a "language construct" and cannot be used on anything besides variables (i.e. can't be used on the return value of a function). Same with empty up until PHP 5.5.

Nicole
  • 32,841
  • 11
  • 75
  • 101
3

If you want to see if a variable exists, use isset(), and defined() only applies to constants.

If you want to check if a constant is empty, you can not use:

if (empty(B)) // syntax error
if (empty(constant('B'))) // fatal error

You can convert the constant to boolean:

if((boolean) A) {
}

So, you can change your code to:

<?php
define("SCRIPT_URL", "");
function ifScriptFolder() {
    if(defined('SCRIPT_URL') && !((boolean)SCRIPT_URL)) {
        echo "/".SCRIPT_URL."/";
    } else {
        echo "/";
    }
}
srain
  • 8,944
  • 6
  • 30
  • 42