从外部访问类变量

时间:2014-02-28 17:05:22

标签: php class variables scope

如何在不在PHP中创建新实例的情况下从外部访问类变量?像这样:

class foo
{
    public $bar;
}

echo foo::$bar;

是否可以或者我必须创建将打印或返回此值并使用它或创建新实例($a = new foo; echo $a->$bar)的方法?

编辑:我不想创建将在以后更改的常量变量而是经典变量。

5 个答案:

答案 0 :(得分:0)

IF 使用静态变量是有意义的:

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

可以这样访问:

echo foo::$bar;

答案 1 :(得分:0)

将此变量设为静态以使用类对象访问它。

如果您想通过方法更改静态变量值,则需要使用静态方法

你可以这样试试:

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

输出:changed :)

演示:https://eval.in/107138

你也可以不用静态方法改变它:

foo::$bar = "changed";

演示:https://eval.in/107139

像这样:

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

输出:google

演示:https://eval.in/107126

答案 2 :(得分:0)

如果在运行时期间值永远不会改变,那么您可能希望类常量(http://www.php.net/oop5.constants

class foo {
    const bar = 'abc';
}

...否则你想要一个公共静态变量(http://www.php.net/manual/en/language.oop5.static.php

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

......无论哪种方式,都可以像这样访问

echo foo::bar;

答案 3 :(得分:0)

只有当变量标记为static:

时,才能访问类变量而不创建实例
class foo
{
  public static $bar;
}

答案 4 :(得分:0)

这是你使用类变量的方法:

// 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);

这就是你如何从随机类名字符串变量实例化一个类。

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

你的实际问题是什么?