0

So I have this simple code:

<?php

class TestClass {

    public function test_function($id, $values = array()) 
    {
        
        $ref_met = new ReflectionMethod(__METHOD__);
        foreach($ref_met->getParameters() as $param) {
            if($param->isArray()) {
                echo "$param->name is an array\n";
            } else {
                echo "$param->name is NOT an array\n";
            }
        }       
    }

}

$t = new TestClass();
$t->test_function(5, array());

The $values method argument is an array, you can tell in the function definition, however, if I use reflection to get the method parameters information they always return as not being an array.

I can try even extracting the reflection relevant code to another separate function so that It does not execute on the method itself, but to no avail:

<?php

class TestClass {

    public function test_function($id, $values = array()) 
    {
                
    }

}

function test_reflection() 
{
    $ref_met = new ReflectionMethod('TestClass::test_function');
    foreach($ref_met->getParameters() as $param) {
        if($param->isArray()) {
            echo "$param->name is an array\n";
        } else {
            echo "$param->name is NOT an array\n";
        }
    }
}


test_reflection();

Is there something I'm not understanding about reflection on PHP? I've read and re-read the documentation but I can't find anything that tells me I'm doing something wrong.

I'm using PHP 5.4.20, if that matters.

1 Answer 1

2

Because RelectionParameter::isArray() checks if the method expects if the parameter is an array. Not if the method is defaulted to be an array. It is examining for the type hint not the default parameter. Without the hint, the parameter can be anything so the isArray check will be false. The value is just defaulted to an empty array if nothing is provided for the parameter but as your signature is right now it could be anything.

https://www.php.net/manual/en/reflectionparameter.isarray.php

TRUE if an array is expected, FALSE otherwise.

Make your class like this and it will be true:

class TestClass {

    public function test_function($id, array $values = array()) 
    {

    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

A newcomer thing I guess, did not know that you could hint types to arguments. Is this only possible with arrays or can you actually do it with any type?
php.net/manual/en/language.oop5.typehinting.php You can type hint objects, interfaces, arrays or callbacks (as callable).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.