繁体   English   中英

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

[英]Call a class inside another class in PHP

嘿那里我想知道这是怎么做的,因为当我在类的函数内尝试以下代码时它会产生一些我无法捕获的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();

你不能在类的方法(函数)中声明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();

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

public $tasks;
$this->tasks = new tasks();
$this->tasks->test();
$this->showPanel();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM