我可以使用变量而不用PHP中的$ this-> myvar来声明吗?

shi*_*hin 0 php variables

在下面的代码中,变量user和permission在开头没有声明,如$ data,$ module等.这些$ this-> user和$ this-> permissions在此类的扩展类中使用.

我的问题是我可以在不声明和使用$ this-> myvar的情况下使用变量吗?

提前致谢.

class MY_Controller extends CI_Controller {

// Deprecated: No longer used globally
protected $data;
public $module;
public $controller;
public $method;

public function MY_Controller()
{
      .......
     $this->user = $this->ion_auth->get_user();
     .........
     // List available module permissions for this user
    $this->permissions = $this->user ? 
     $this->permission_m->get_group($this->user->group_id) : array();
Run Code Online (Sandbox Code Playgroud)

Phi*_*hil 5

是的你可以.

PHP在初始设置时自动创建公共属性,例如

class MyClass
{
    private $foo;

    public function __construct()
    {
        $this->bar = 'bar'; // Now contains "public $bar"
    }
}
Run Code Online (Sandbox Code Playgroud)

唯一不同的是,如果您有一个魔术__set($name, $value)方法,它会捕获尝试写入未定义或不可见(在当前范围内)属性.