Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php: get variable type hint using reflection

class Expense {

    /**
     * @var int
     */
    private $id;
}

I would like to obtain the type hint of a variable in my class, using reflection, because the default value is null.

like image 893
yelo3 Avatar asked Jun 06 '11 09:06

yelo3


1 Answers

Try:

<?php
class Expense {

    /**
     * @var int
     */
    private $id;
}

$refClass = new ReflectionClass('Expense');
foreach ($refClass->getProperties() as $refProperty) {
    if (preg_match('/@var\s+([^\s]+)/', $refProperty->getDocComment(), $matches)) {
        list(, $type) = $matches;
        var_dump($type);
    }
}

Output:

string(3) "int"
like image 135
Yoshi Avatar answered Sep 17 '22 19:09

Yoshi