PHP中$this的作用域是什么?


what is scope of $this in php in oop

$this在php中的作用域是什么,我们可以在类

中声明外部函数吗?
class Blogs extends Controller
{
     public  $articlesmodel = $this->loadmodel('articlesmodel');
     public function index()
     {      
          if(!isset($_SESSION['user']['login_id'])){
            header("location:".URL);
           }
     }
}

对于Blogs类,它将位于类边界上。但你也是extending Controller班的。所以有了$this,你可以访问所有的public &Controller类的protected成员。

在上面的代码中,$this->loadmodel('articlesmodel');正在访问Controller类的方法(如果Controller类没有扩展任何包含该方法的其他类)。

变量声明中不能有表达式或函数调用。对于错误do -

class Blogs extends Controller
{
     public $articlesmodel;
     function __construct()
     {
        $this->articlesmodel = $this->loadmodel('articlesmodel');
     }
     public function index()
     {      
          if(!isset($_SESSION['user']['login_id'])){
            header("location:".URL);
           }
     }
}

$this表示类本身的实例,因此您可以访问该类中的任何内容,包括私有变量,函数等。

使用$this来引用当前对象。使用self来引用当前类。换句话说,对于非静态成员使用$this->member,对于静态成员使用self::$member。

$this = current class