嘿那里我想知道这是如何完成的,因为当我在类的函数中尝试以下代码时它会产生一些我无法捕获的php错误
public $tasks;
$this->tasks = new tasks($this);
$this->tasks->test();
我不知道为什么类的启动需要$ this作为参数:S
感谢
class admin
{
function validate()
{
if(!$_SESSION['level']==7){
barMsg('YOU\'RE NOT ADMIN', 0);
return FALSE;
}else{
**public $tasks;** // The line causing the problem
$this->tasks = new tasks(); // Get rid of $this->
$this->tasks->test(); // Get rid of $this->
$this->showPanel();
}
}
}
class tasks
{
function test()
{
echo 'test';
}
}
$admin = new admin();
$admin->validate();
答案 0 :(得分:24)
你不能在你的类的方法(函数)中声明public $ tasks。如果你不需要在该方法之外使用tasks对象,你可以这样做:
$tasks = new Tasks($this);
$tasks->test();
您只需要使用“$ this->”当你使用一个你希望在整个班级可用的变量时。
您有两个选择:
class Foo
{
public $tasks;
function doStuff()
{
$this->tasks = new Tasks();
$this->tasks->test();
}
function doSomethingElse()
{
// you'd have to check that the method above ran and instantiated this
// and that $this->tasks is a tasks object
$this->tasks->blah();
}
}
或
class Foo
{
function doStuff()
{
$tasks = new tasks();
$tasks->test();
}
}
代码:
class Admin
{
function validate()
{
// added this so it will execute
$_SESSION['level'] = 7;
if (! $_SESSION['level'] == 7) {
// barMsg('YOU\'RE NOT ADMIN', 0);
return FALSE;
} else {
$tasks = new Tasks();
$tasks->test();
$this->showPanel();
}
}
function showPanel()
{
// added this for test
}
}
class Tasks
{
function test()
{
echo 'test';
}
}
$admin = new Admin();
$admin->validate();
答案 1 :(得分:5)
问题在于这行代码:
public $tasks;
$this->tasks = new tasks();
$this->tasks->test();
$this->showPanel();
public
关键字用于类的定义,而不是类的方法。在php中,你甚至不需要在类中声明成员变量,只需执行$this->tasks=new tasks()
就可以为你添加它。