Call a class inside another class in PHP

后端 未结 2 2019
清酒与你
清酒与你 2021-02-04 08:58

Hey there I\'m wondering how this is done as when I try the following code inside a function of a class it produces some php error which I can\'t catch

public $t         


        
2条回答
  •  抹茶落季
    2021-02-04 09:20

    You can't declare the public $tasks inside your class's method (function.) If you don't need to use the tasks object outside of that method, you can just do:

    $tasks = new Tasks($this);
    $tasks->test();
    

    You only need to use the "$this->" when your using a variable that you want to be available throughout the class.

    Your two options:

    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();
        }
    
    }
    

    or

    class Foo
    {
        function doStuff()
        {
            $tasks = new tasks();
            $tasks->test();
        }
    }
    

    with your code:

    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();
    

提交回复
热议问题