Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Reflection - Get Method Parameter Type As String

Tags:

php

reflection

I'm trying to use PHP reflection to dynamically load the class files of models automatically based upon the type of parameter that is in the controller method. Here's an example controller method.

<?php

class ExampleController
{
    public function PostMaterial(SteelSlugModel $model)
    {
        //etc...
    }
}

Here's what I have so far.

//Target the first parameter, as an example
$param = new ReflectionParameter(array('ExampleController', 'PostMaterial'), 0);

//Echo the type of the parameter
echo $param->getClass()->name;

This works, and the output would be 'SteelSlugModel', as expected. However, there is the possibility that the class file of the model may not be loaded yet, and using getClass() requires that the class be defined - part of why I'm doing this is to autoload any models that a controller action may require.

Is there a way to get the name of the parameter type without having to load the class file first?

like image 699
Jarrod Nettles Avatar asked Dec 22 '10 21:12

Jarrod Nettles


People also ask

What does :: class do in PHP?

::class ¶ The class keyword is also used for class name resolution. To obtain the fully qualified name of a class ClassName use ClassName::class . This is particularly useful with namespaced classes.

What is reflection of parameters?

The ReflectionParameter class retrieves information about function's or method's parameters. To introspect function parameters, first create an instance of the ReflectionFunction or ReflectionMethod classes and then use their ReflectionFunctionAbstract::getParameters() method to retrieve an array of parameters.

What is reflection method in PHP?

The term “reflection” in software development means that a program knows its own structure at runtime and can also modify it. This capability is also referred to as “introspection”. In the PHP area, reflection is used to ensure type safety in the program code.

What is reflection class PHP?

The ReflectionClass::getProperties() function is an inbuilt function in PHP which is used to return an array of the reflected properties. Syntax: ReflectionClass::getProperties($filter) : array. Parameters: This function accepts a parameter filter which helps to remove some of the reflected properties.


1 Answers

I think the only way is to export and manipulate the result string:

$refParam = new ReflectionParameter(array('Foo', 'Bar'), 0);

$export = ReflectionParameter::export(
   array(
      $refParam->getDeclaringClass()->name, 
      $refParam->getDeclaringFunction()->name
   ), 
   $refParam->name, 
   true
);

$type = preg_replace('/.*?(\w+)\s+\$'.$refParam->name.'.*/', '\\1', $export);
echo $type;
like image 81
netcoder Avatar answered Oct 02 '22 09:10

netcoder