$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