Jump to content

Best way to call a class from within a class


scrubbicus

Recommended Posts

So I have a users class that I want to call within my data class. What's the best way to do this?

 

Currently I have, and it works.

 

public function __construct() {

  $this->_users = new users;

}

 

then I can call it as needed from within the class but now that class is being called TWICE so anything I have within the constructer user will be done twice. Is there any other ways I can use a class within another class?

Link to comment
Share on other sites

Like for instance if you had two classes and you had a function that was in one of the classes that you wanted to use in the other class. What would be all the ways, or the best way, to accomplish creating a new instance of that class and calling it from within that class.

 

 

Link to comment
Share on other sites

Long version:

Well it depends, are you programming like an object oriented programmer? If so, you should be creating objects and performing actions ON those objects, not just calling methods IN them. At that point it should be clear whether you want to create a new copy of an object or pass the routine an existing one and you probably wouldn't need to be asking us this question.

 

If all you're doing is taking your procedural program and putting it inside of classes, then you're not programming like an object oriented programmer and it would be less confusing to just make the classes/methods static so you don't have to instantiate them to begin with. Once you reach that point, you might just raise the question of "why don't I just program procedurally to begin with?"

 

Short version:

If you find yourself creating new classes just to use the methods inside of them and not because you're trying to represent a new "user" or whatever it is your class is supposed to represent, it should probably be a static method. Or, more likely, you're not designing the program in a proper object-oriented manner to begin with.

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.