在PHP中调用另一个类中的类

Sup*_*vah 9 php abstract-class class

嘿那里我想知道这是怎么做的,因为当我在类的函数内尝试以下代码时它会产生一些我无法捕获的php错误

public $tasks;
$this->tasks = new tasks($this);
$this->tasks->test();
Run Code Online (Sandbox Code Playgroud)

我不知道为什么类的启动需要$ 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();
Run Code Online (Sandbox Code Playgroud)

Lan*_*ell 24

你不能在类的方法(函数)中声明public $ tasks.如果你不需要在该方法之外使用tasks对象,你可以这样做:

$tasks = new Tasks($this);
$tasks->test();
Run Code Online (Sandbox Code Playgroud)

当您使用想要在整个班级中可用的变量时,您只需要使用"$ 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();
    }

}
Run Code Online (Sandbox Code Playgroud)

要么

class Foo
{
    function doStuff()
    {
        $tasks = new tasks();
        $tasks->test();
    }
}
Run Code Online (Sandbox Code Playgroud)

用你的代码:

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();
Run Code Online (Sandbox Code Playgroud)


dav*_*nal 5

你遇到的问题是这行代码:

public $tasks;
$this->tasks = new tasks();
$this->tasks->test();
$this->showPanel();
Run Code Online (Sandbox Code Playgroud)

public关键字在类的定义中使用,而不是在类的方法.在php中,你甚至不需要在类中声明成员变量,你可以这样做,$this->tasks=new tasks()并为你添加它.