from http://www.php.net/manual/en/class.pdo.php
###### config.ini ######
db_driver=mysql
db_user=root
db_password=924892xp
[dsn]
host=localhost
port=3306
dbname
A singleton is a software design pattern that restricts the initiation of a class to one instance. http://en.wikipedia.org/wiki/Singleton_pattern
Static means that something belongs to the class and not a particular instance. In PHP, this also means that a static method needs to be called with ::
not ->
_callStatic returns the PDO link if it has already been established. Otherwise, it first creates the link and then returns it.
The answer to your fourth question is precisely the singleton pattern. It ensures that the connection is only set up once, when needed.
A singleton is an object that ensures that only one instance of itself is active at a time. That is, you can only make one per program, if you know what I mean.
A static method is one that can be called like a normal function, outside of object context. Like SomeClass:afunc()
and not only $this->afunc()
.
A single ton is a static function that allows you to keep track of your object instances, when you use a singleton you create an instance of the object but the instances always stays with the associated object.
Take this example:
$db1 = new Database();
$db2 = new Database();
as you can see that db1
and db2
are 2 new instances of Database therefore there not the same, now take this example.
$db1 = Database::Instance();
$db2 = Database::Instance();
And the code for Instance
class Database
{
private static $_instance;
public static Instance()
{
if(self::$_instance !== null)
{
//We have already stored the object locally so just return it.
//This is how the object always stays the same
return self::$_instance;
}
return self::$_instance = new Database(); //Set the instance.
}
}
If you analyse the code you will so that no matter where you use Instance throughout your application your object will always be the same.
a static function is a method within a class/object isa type of method that can be used without the object being initialized.
In regards to __callStatic method, this is a Magic Method that's executed where a static method is not available.
For example:
class Database
{
public static function first()
{
echo 'I actually exists and I am first';
}
public function __callStatic($name,$args)
{
echo 'I am '. $name .' and I was called with ' . count($args) . ' args';
}
}
lets test them.
Database::first(); //Output: I actually exists and I am first
Database::second(); //Output: I am second and I was called with 0 args
Database::StackOverflow(true,false); //Output: I am StackOverflow and I was called with 2 args
Hope this helps you