简体   繁体   中英

Access to class variable from outside

How can I access to class variable from outside without creating new instance in PHP ? Something like this:

class foo
{
    public $bar;
}

echo foo::$bar;

Is it possible or I must create method that will print or return this value and use it or create new instance ( $a = new foo; echo $a->$bar ) ?

EDIT: I don't want to create constant but classic variable that will be changed later.

IF it makes sense to use a static variable:

class foo{
    public static $bar = 'example';
}

Which could be accessed like so:

echo foo::$bar;

make this variable static to access it with out class object.

If you wanted to change static variable value by method then you need to use static method

you can try like this:

class foo
{
  public static $bar ="google";
  public static function changeVal($val){
   self::$bar=$val;
  }
}
 foo::changeVal("changed :)");
 echo foo::$bar;

Output : changed :)

Demo : https://eval.in/107138

You also can changed it like this without static method:

foo::$bar = "changed";

demo : https://eval.in/107139

like this:

class foo
{
  public static $bar ="google";
}
echo foo::$bar;

Output: google

demo: https://eval.in/107126

If the value will never change during runtime, then you probably want a class constant ( http://www.php.net/oop5.constants )

class foo {
    const bar = 'abc';
}

...otherwise you want a public static variable ( http://www.php.net/manual/en/language.oop5.static.php )

 class foo {
    public static $bar = 'abc';
}

...either way, access it like this

echo foo::bar;

You can access the class variable without creating instances only when the variable is markesd as static:

class foo
{
  public static $bar;
}

This is how you use a class variable:

// with instantiation
class foo {
    // initialize on declare
    public $bar = 1;
    // or initialize in __construct()
    public function __construct(){
        $this->bar = 1;
    }
}
$foo = new foo();
var_dump($foo->bar);

// static way
class static_foo {
    public static $bar = 1;
}
var_dump(static_foo::$bar);

And this is how you instantiate a class from a random class name string variable.

$foo = new foo();
$random_class_name = $foo->bar;
try {
    // following line throws if class is not found
    $rc = new \ReflectionClass($random_class_name);
    $obj = $rc->newInstance();
    // can be used with dynamic arguments
    // $obj = $rc->newInstance(...);
    // $obj = $rc->newInstanceArgs(array(...));
} catch(\Exception $Ex){
    $obj = null;
}
if($obj){
    // you have a dynamic object
}

What's your actual question?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM