get current instance of class in PHP - php

how do i get access to a current instance of class that's already running in PHP?
in my one PHP class, I want to call a function from another that's already running as a server. so i cant create a new instance.
thanks.
p a

What you want is called a singleton.
With a Singleton you can have only one instance of your class running on the server.
To do so you must :
store your instance in your class as a static field
have a private constructor so you can't create instances yourself
have a static method which call the constructor once, and return the only instance
Resources :
Wikipedia - Singleton pattern
php.net - singleton
On the same topic :
Creating the Singleton design pattern in PHP5
What is so bad about Singletons

Related

oop php constructor access modifier, which one to use?

I've just started experimenting with OO PHP, but there's one basic principle I don't really uderstand that well, and don't find too much info on it.
When creating a __construct() method, why would you want it to be public, when it's specifically a constructor for that class?
When would you want to call a constructor outside the class?
To me, it seems using a protected constructor is good practice, right?
I know this is basic OO stuff, but I don't find any info directly on it, specifically for constructors.
The __construct (not "__constructor") method is the one called when you do new MyClass(), i.e. when you instantiate the class. The constructor needs to be public, unless you only want to instantiate the class from within itself. If the latter, you need at least one other public static method you can call in which the class will instantiate itself, otherwise you're unable to create any instance of it.
Whenever you create a new instance of a class, the constructor is called. If the constructor is not public, no other code can create an instance of that class.
Hence, if you want to create instances of the class, make the constructor public.
A constructor is always only part the class it is defined in, I don't understand what you mean by "when it's specifically a constructor for that class".
To clarify:
The only way to invoke the constructor is with new Class(). There is no other way to invoke it. __construct is a magic method and there is no way to explicitly call a magic method.

PHP: share database connections or create new one?

I have been advice not to use the singleton pattern for my data base class. I have not fully understand what are the cons to it, anyway there seems to be agreement in this point so I follow the rule.
But, is sharing instances of classes a bad habit in PHP in general? Which is best from the two examples provide here? I am using in fact the singleton pattern with the first approach?
//semi-pseudo Code
Class DB extends mysqli{
//
}
Class A {
$db; //Of type Class DB, initialized in the constructor.
//In some method
//Should I do this, so sharing the data base connection?
$b = new DB( $db );
// OR
// Should I instantiate a new instance?
$newDb = new DB();
$b = new B ($newDb);
}
Class B {
$db;//Of type Class DB initialized in the constructor.
I have a Class DB being a data base extension..
I have Class A with a member of type DB.
Class A needs to create an instance of Class B, which in turn also has a member of type DB.
I'm using the Dependency Injection pattern so A should pass a DB instance to B.
Should I instantiate a new DB instance to pass to B, or can I just pass a reference to A's DB instance.
There's nothing wrong with using the Singleton pattern in PHP, like any language, too much of anything likely indicates poor design.
That said, Singleton is well suited to database access. Has anyone justified why it's supposedly a bad idea?
The main argument against Singleton is difficulty to test because you can't mock them with unit test suites. Personally I try to avoid mock objects in my tests (especially w/ PHPUnit), so it usually doesn't matter.
Should I instantiate a new DB instance to pass to B, or can I just
pass a reference to A's DB instance.
Of course you have to pass a reference of A's DB instance to B class.

Php: singleton VS full static class? When use what?

I understand that singleton enforces a class to be created once. But why should an instance exists if I dont access it directly? Why is that pattern for, isn't it easier just use full static class with static methods and datas?
Some time ago I was asked what is the benefit of using singleton over of using static class, here is my response:
Static class leads to invisible dependencies - that is a class that use the static class, but that class is not part of the class' interface.
Singleton also allows this, because it provides global access point, but it's instance can be passed as an argument to the class / method
If there is any initialization, as the connect method, it should be called from each class method, which leads to duplicated code. On the other hand, the initialization of the singleton is performed in the constructor, which is called just once from the getInstance()
method
Singleton can be easily refactored in a factory, adding a parameter to the getInstance() method and returning different instances
Static class is harder to extend, because if we want to override a method, that is called within the class with self::methodName(), we should override the caller as well (although in PHP 5.3 there is a late static binding, which can be used to avoid those problems)
If you need to add an argument, needed for all of the methods, you can easily do this in singleton because of the single access point, but you can't in a static class
The major difference between a static class and a singleton is that with the static class, you need to hardcode the class name in your code everywhere you use it:
StaticClass::doSomething();
StaticClass::doSomethingElse();
While with a singleton, you only need to hardcode the class name once:
$singleton = SingletonClass::getInstance();
// other code does not need to know where $singleton came from,
// or even that class SingletonClass exists at all:
$singleton->doSomething();
$singleton->doSomethingElse();
Another important difference is that singleton classes can be part of hierarchies and can implement interfaces.
This does not mean that Singleton (the pattern) is good and should be used liberally. But it is better than using a static class directly.
[Edit]: The stuff I have written below is actually plain wrong. Just got alerted to this answer from years ago by a downvote. They do serve a purpose ;)
A singleton exists once, but it can have internal state - as opposed to a static class. You might e.g. use it as a global registry, which you can't do with a static class.
[Edit:] What comes next, though, is as true as it ever was.
It's debatable whether singletons are a good idea, though. They introduce global state into an application, which can make it very hard to test. But that is another discussion.

Pure Static Class vs Singleton

Writing a PHP app and have several classes that only have static methods (no need for instance methods). An example of one is NumericValidator, which has methods like checkInteger($toCheck) which checks to make sure the argument you pass it is of type int, and checkGreaterThan($lOperand, $rOperand), which makes sure that the left operand is greater than the right operand, etc.
I know I could just throw each of these methods into a PHP file without putting them inside of a class, but I want to take an OOP approach here in case the API evolves to require instantiating NumericValidator.
But it does beg the question: how is a class with 100% static methods any different than have a class implement a singleton design pattern, where every reference used throughout the code base invokes the same instance?
For example, here is what my code looks like now:
public function doSomething($p_iNum)
{
if(!NumericValidator::checkInteger($p_iNum))
// throw IllegalArgumentException
// ...
}
But I could turn all of NumericValidator's static methods into non-static instance methods, forcing the programmer to instantiate it, and then implement a singleton design pattern so you can only ever reference 1 instance of it:
public function doSomething($p_iNum)
{
NumericValidator $nv = NumericValidator::getInstance();
if(!nv->checkInteger($p_iNum))
// throw IllegalArgumentException
// ...
}
Finally, my question: which is better and more in keeping with best practices? Are there performance considerations? How would either approach affect things like concurrency, or requests coming from multiple users?
I would use a static class in your example. The differentiator I would use is if there is any state of the properties of an instance you are trying to preserve across access. This is what a singleton is designed for. The static class gives organized access to methods in a namespace which is helpful for clarity in your code but it does not have any properties about itself.
So yes you can use a singleton but it would be bad form because there are no instance properties that you want to make available across page accesses.
Hope this helps.
Use Singleton instead of static class only if you going to pass instance of NumericValidator in variable to some function.
In PHP 5.3 you can get instance of static class:
class test
{
public static function instance()
{
print 'zz';
}
}
$z = new test;
$z->instance();
Don't care about concurrency requests in PHP, it's single threaded, each process executes own code.

difference between object and static methods

What's the difference between static and object methods? Where and why are they used differently? When do I use which one of those?
With object methods you need to instantiate the class in order to use the method so say Bark is an object method
Dog myDog = new Dog();
myDog.Bark();
But now let's say Bark was a static method. I could just do:
Dog.Bark();
So a static method works on a class, not on an object.
Static methods are useful when you'd like to just make a global utility class. That way you don't need to pass an object around just to use methods on this utility class.
static methods are instantiated only once in the memory space.
Instance methods require an instance of the class to be invoked. The instance reference can be thought of as an invisible first parameter, which can be accessed within the method using the 'this' keyword in C#, C++, and Java. Static methods can be invoked without an instance of the class. They can only access instances of the class if they are passed in as parameters.
As a general rule of thumb, use an instance method when the method performs some operation on a single instance. Use a static method when the method performs an operation on multiple instances, or requires no instances.
PHP manual is very brief about that. But static is explained quite well in the book "PHP 5 Power Programming":
Static properties
Static methods
Singleton pattern (scroll down to the singleton section there)

Categories