Olaf Erlandsen
Olaf Erlandsen

Reputation: 6036

Reflection class PHP from file?

I wanna get value from Class PHP without initialize this Class. For this I give the file path where this class, for it to be reviewed, but not initialized.

My Idea:

<?php
$reflection = new ReflectionClass( '/var/www/classes/Base.php' );
$version = $reflection->getProperty('version')->getValue(  );

if( $version >= 1 )
{
    return true;
}
return false;
?>

BASE.PHP

<?php
class Base
{
    private $version = 2;
}
?>

Upvotes: 5

Views: 3984

Answers (2)

S&#233;bastien Renauld
S&#233;bastien Renauld

Reputation: 19662

How about a protected variable with a getter.

class Base {
    protected $version = array(2,3,4,5,6);
    public function __version() { return $this->version; }
}

You can instantiate this anywhere you like, or extend it to add functions to it. The version will be constant across any extensions, so bear that in mind.

Usage is as simple as $yourClass->__version(). Named it similar to a magic method's name in order to prevent function name collision. It can be redefined by extensions if needed.

Upvotes: 1

steven
steven

Reputation: 4875

whats about static? its much simpler:

<?php
class Base
{
    public static $version = 2; // or $version = array(1,2,3);
}

if(is_array(Base::$version)) {
    print_r(Base::$version);
} else {
    echo Base::$version;
}

?>

Upvotes: 1

Related Questions