Object assignment in class-problem

A

Anonymous

Guest
I have a class, foo, and a class, bar, and in the bar class, one of the variables are initiated as an object of the class foo like this:

Code:
class foo
{
  var $owner;
  function foo($x)
  {
    $this->owner=$x;
  }
}

class bar
{
  var $baz=new foo($this);
  ...
}

The idea is that foo is to be "owned" by bar.
Whenever I do this though, the script is aborted, with no error message neither, probably because the admin have removed those for the looks... :roll:
I tried error_reporting(E_ALL) though, but still get no error message.

It's not critical, but it would sure make my life, and my project, a bit better... :?
 
maybe i am seeing wrong but both your classes are foo.... 8O
 
You must use a constructor function.
Code:
class foo 
{ 
  var $owner; 
  function foo($x) 
  { 
    $this->owner=$x; 
  } 
} 

class bar 
{ 
  var $baz;
  function bar()
 {
    $this->baz =new foo($this); 
 }
}

It's also good practice to start your class names with a capital letter.
 
OK, it works that way, thanks for the help.
But I still can't see why it shouldn't be able to work as I wrote? :?
 
Papapishu said:
OK, it works that way, thanks for the help.
But I still can't see why it shouldn't be able to work as I wrote? :?

$this refers to an instance of the class. Without a constructor, you can't create an instance, so you don't have access to $this. PHP doesn't have class variables, only instance variables.
 
Back
Top