views:

153

answers:

1

Hello, I'm building my own framework, and I'm trying to pass a parameter to a static method. For some reason, the parameter is not getting passed. Here is the code:

Front.php:

if(URI::get(0) === "")

URI.php:

public static function get($index)
    {
        die($index);
        if(!filter_var($index, FILTER_VALIDATE_INT)) {
            throw new Exception('You must supply an integer index for the URI segment');
        }

        return self::$uri[$index];
    }

At first I was getting an exception, so I added in the die statement to make sure the $index was actually getting passed correctly. Apparently it's not because when the script exits, nothing gets printed out for the index.

I am using php 5.3.1.

+2  A: 

This is rather odd, as it should work ; after testing this portion of code :

class ClassA {
    public static function a($param) {
        var_dump($param);
    }
}

ClassA::a(123);

I get this output :

int 123

Which indicates the static method did indeed receive the parameter (and I see no reason why it shouldn't, actually).


As a sidenote, you are ending with this portion of code :

die(0);

Quoting the manual page for exit (which is the same as die) *(emphasis mine)* :

void exit  ([ string $status  ] )
void exit ( int $status )

If status is a string, this function prints the status just before exiting.
If status is an integer, that value will also be used as the exit status.
[...]
Note: PHP >= 4.2.0 does NOT print the status if it is an integer.

You are using PHP 5.3, which is a more recent version than 4.2 ; and, in your case, $status is an integer -- which means it is perfectly normal to not have anything displayed, with the code your posted.


And, to finish : if you remove the die, your code ends up doing this :

if(!filter_var($index, FILTER_VALIDATE_INT)) {
    throw new Exception('...');
}

With $index = 0

filter_var returns the filtered value ; using FILTER_VALIDATE_INT, I suppose you are filtering to get an integer -- and 0 is integer.

Which means your call to filter_var will return 0.

0 is considered as false (see Converting to boolean) -- so, you will enter into the if block ; and the exception will be thrown.


Considering filter_var returns :

  • The filtered data,
  • or false when the filter failed,
  • And that 0 is a valid data that can be returned,

You should probably use the === operator (see Comparison Operators), to compare the returned value to false. Which means some code that would look like this :

if(filter_var($index, FILTER_VALIDATE_INT) === false) {
    throw new Exception('...');
}


Hope this helps !

Pascal MARTIN
Thanks for the response, I added an echo instead of a die, and the 0 is getting passed in...Unfortunately the exception is getting thrown which means that it doesn't think that 0 is an int.
adaykin
Ahh didn't see the last part, got it working now, thanks!
adaykin
You're welcome :-) Have fun !
Pascal MARTIN