Jump to content

Archived

This topic is now archived and is closed to further replies.

HGeneAnthony

Can I call a class from a class?

Recommended Posts

I was working with classes in PHP and one thing I generally do is call a class from another class. However, I seem to get the error:

Parse error: parse error, unexpected T_NEW in /www/phpproject/index.php on line 11

I had typed the class:

class Test {
private $user = new User("gene", "password");
}

Is there a way I can make this work? Also, in the User class (due my Java background) I used a constructor with the same name as the class (IE. function User($x, $y)), However, I noticed PHP has the method __construct. However I noticed my way worked. Is it appropriate to use either or, or should I avoid using the same method name as the class in case it's taken out in the future.

Share this post


Link to post
Share on other sites
You'd be best to define User in tests construct.
[code]
class Test {

  private $user;

  function __construct() {
    $this->user = new User("gene", "password");
  }

}
[/code]
Also note that the __construct is only available in php5. If your using an older version you'll need to make a method with the same name as the class as you did above.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.