Reputation: 2466
I'm using OOP aproach in php.I'm just learning though. Each time I need to access a method in a class I instantiate a object.So I have quite a number of objects created in my project to do each task.Is there a way where I can only create one object and share throughout the project to do multiple method for different task?
Also in my class, I declared the variable first and then use them like $this->property = $assign_variable
.Will declaring variable earlier would consume memory much?
I'm just concerned to approach the right and effective way of instantiating object and declaring class in OOP. Can anyone suggest please?
Upvotes: 1
Views: 1028
Reputation: 938
Having multiple instances of an object consumes more memory (much is relative), as every attribute of an object needs to have allocated memory. If you have an object that consumes, lets say, x bytes of memory for its attributes, then you will need n*x bytes of memory if you instantiate n objects in total (There is also a neglactable amount of memory used which needs to be used for the code, but the amount is constant). In normal use that shouldn't be a problem though (i.e. if you don't have an unusual huge amount of objects).
If you need only one instance of a class through the whole program, I'd suggest you to use the Singleton design pattern 1].
Here is an example:
class Singleton {
// This is where the one and only instance is stored
private static $instance = null;
private __construct() {
// Private constructor so the class can't be initialized
}
// That's how you get the one and only instance
public static function getInstance() {
if (Singleton::$instance === null) {
Singleton::$instance = new Singleton();
}
return Singleton::$instance;
}
public function doSomething() {
// here you can do whatever you need to do with the one and only object of this class
}
}
You can then use it very conveniently like this:
Singleton::getInstance()->doSomething();
So you are basically just storing the address of the object in one location, namely Singleton::$instance
.
Another option for you could be to use static methods. It is defined like above in the Singleton pattern:
class StaticExample {
// ...
public static function doSomething() {
// your code
}
}
And can be accessed with StaticExample::doSomething();
I also want to note that usually, you don't have much classes in a project which implements the Singleton design pattern or use the static
keyword very often. If you want to use a lot of singletons or see yourself needing a lot of static
s, you probably got something wrong and should post an example of your code on another site like Programmers Stack Exchange.
1] Singleton design pattern on Wikipedia
Upvotes: 4