PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

[FIXED] How to get parameter type in reflected class method (PHP 5.x)?

 July 22, 2022     parameters, php, php-5.4, reflection     No comments   

Issue

I'm trying to get type $bar variable.

<?php
class Foo
{
    public function test(stdClass $bar, array $foo)
    {

    }
}

$reflect = new ReflectionClass('Foo');
foreach ($reflect->getMethods() as $method) {
    foreach ($method->getParameters() as $num => $parameter) {
        var_dump($parameter->getType());
    }
}

I expect stdClass but I get

Call to undefined method ReflectionParameter::getType()

What can be wrong? Or there is some another way?..

$ php -v
PHP 5.4.41 (cli) (built: May 14 2015 02:34:29)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies

UPD1 It should work for the array type as well.


Solution

It looks like similar question already added in PHP Reflection - Get Method Parameter Type As String

I wrote my solution it works for all cases:

/**
 * @param ReflectionParameter $parameter
 * @return string|null
 */
function getParameterType(ReflectionParameter $parameter)
{
    $export = ReflectionParameter::export(
        array(
            $parameter->getDeclaringClass()->name,
            $parameter->getDeclaringFunction()->name
        ),
        $parameter->name,
        true
    );
    return preg_match('/[>] ([A-z]+) /', $export, $matches)
        ? $matches[1] : null;
}


Answered By - Kirby
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing