5

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;
}
?>
4
  • let us know if it works when you try it? Commented May 30, 2013 at 20:33
  • 2
    What are you trying to do? Why not make it a public constant? Commented May 30, 2013 at 20:33
  • 2
    If you're doing this for performance, you should know that loading Reflection is way heavier than simply creating the class, getting the property and then deleting it. Commented May 30, 2013 at 20:33
  • Guys, i need use a Array on the variable. Example: $version = array(1,2,3,4,5,6,7,8,9,...); OR int value. Commented May 30, 2013 at 20:37

2 Answers 2

1

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;
}

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

3 Comments

...And requires you to know the exact name of the class.
@SébastienRenauld Not any more than with your solution. The following would output '2': class Base { public static $version = 2; } $o = new Base; print_r($o::$version);. You just have to know that it's static!
How does it answer the question to take a file and extract class from it?
1

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.

Comments

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.