views:

756

answers:

2

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 $tasks;
$this->tasks = new tasks($this);
$this->tasks->test();

I don't know why the initiation of the class requires $this as a parameter either :S

thanks

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();
+3  A: 

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();
Lance Kidwell
it didn't work. I just updated my question with a more verbose copy of my code
Supernovah
thanks for the work u just did :)
Supernovah
+2  A: 

You're problem is with this line of code:

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

The public keyword is used in the definition of the class, not in a method of the class. In php, you don't even need to declare the member variable in the class, you can just do $this->tasks=new tasks() and it gets added for you.

notJim