PHP类中的可变范围

Dou*_*eux 10 php scope

如何在此类中设置全局变量?我试过这个:

class myClass
{
   $test = "The Test Worked!";
   function example()
   {
      echo $test;
   }
   function example2()
   {
      echo $test." again";
   }
}
Run Code Online (Sandbox Code Playgroud)

哪个无法加载页面完全引用500错误.接下来我尝试了这个:

class myClass
{
   public $test = "The Test Worked!";
   function example()
   {
      echo $test;
   }
   function example2()
   {
      echo $test." again";
   }
}
Run Code Online (Sandbox Code Playgroud)

但是当我打印这两个时,我所看到的只是"再次"抱歉这么简单的问题!

谢谢!

Ish*_*Ish 20

这个变量可以像这样访问

echo $this->test;
Run Code Online (Sandbox Code Playgroud)


小智 9

如果需要实例变量(仅为该类的实例保留),请使用:

$this->test
Run Code Online (Sandbox Code Playgroud)

(另有答案建议.)

如果你想要一个"class"变量,请在前面添加"static"关键字,如下所示:

类变量与实例变量不同,因为从类创建的所有对象实例将共享同一个变量.

(注意访问类变量,使用类名,或'self'后跟'::')

class myClass
{
   public static $test = "The Test Worked!";
   function example()
   {
      echo self::$test;
   }
   function example2()
   {
      echo self::$test." again";
   }
}
Run Code Online (Sandbox Code Playgroud)

最后,如果你想要一个真正的常量(不可更改),在前面使用'const'(再次使用'self'加上'::'加上常量的名称(虽然这次省略'$'):

class myClass
{
   const test = "The Test Worked!";
   function example()
   {
      echo self::test;
   }
   function example2()
   {
      echo self::test." again";
   }
}
Run Code Online (Sandbox Code Playgroud)


Pat*_*ick 6

实际上有两种方法可以从类内或类外访问类中的变量或函数,如果它们请求项是公共的(或在某些情况下受保护)

class myClass
{
   public $test = "The Test Worked!";
   function example()
   {
      echo $this->test;
      // or with the scope resolution operator
      echo myClass::test;
   }
   function example2()
   {
      echo $this->test." again";
      // or with the scope resolution operator
      echo myClass::test." again";
   }
}
Run Code Online (Sandbox Code Playgroud)


dec*_*eze 5

class Foo {

    public $bar = 'bar';

    function baz() {
        $bar;  // refers to local variable inside function, currently undefined

        $this->bar;  // refers to property $bar of $this object,
                     // i.e. the value 'bar'
    }
}

$foo = new Foo();
$foo->bar;  // refers to property $bar of object $foo, i.e. the value 'bar'
Run Code Online (Sandbox Code Playgroud)

请从这里开始阅读:http://php.net/manual/en/language.oop5.basic.php