Jump to content

Can I call a class from a class?


HGeneAnthony

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.
Link to comment
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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.