0

I saw a code like this in starttutorial.com:

class Database
{
    private static $dbName = 'crud_tutorial' ;
    private static $dbHost = 'localhost' ;
    private static $dbUsername = 'root';
    private static $dbUserPassword = 'root';

    private static $cont  = null;

    public function __construct() {
        die('Init function is not allowed');
    }
}
public static function connect()
{
   // One connection through whole application
   if ( null == self::$cont )
   {     
    try
    {
      self::$cont =  new PDO( "mysql:host=".self::$dbHost.";"."dbname=".self::$dbName, self::$dbUsername, self::$dbUserPassword);  
    }
    catch(PDOException $e)
    {
      die($e->getMessage()); 
    }
   }
   return self::$cont;
}

and somewhere in the middle of the php file that included this class. I saw this line of code.

$pdo = Database::connect();

From what i know, the __construct method is called when an instance of this class is instantiated. My question is, will the code above call the magic method?

Errol Paleracio
  • 614
  • 1
  • 7
  • 21
  • Not if no new object instance is created inside the `connect()` method - essentially they're creating a static class : http://stackoverflow.com/questions/468642/is-it-possible-to-create-static-classes-in-php-like-in-c (presumably the class example here is a snippet) – CD001 Mar 14 '16 at 10:24
  • where is connect() method? – Gouda Elalfy Mar 14 '16 at 10:25
  • My bad, Didn't paste all the code. done editing now – Errol Paleracio Mar 14 '16 at 10:32
  • Have you tried the code?? I believe it will work but the best way is to try it :o) But in answer to your indirect question - the constructor won't be called. – Ukuser32 Mar 14 '16 at 10:34

1 Answers1

1

will the code above call the magic method?

No because __construct will only be called during class instantiation like below.

$db = new Database();

The time you instantiate a class is the time __construct() is called.

by declaring your methods as static is the time you can use that static method without instantiating your Database class like

Database::connect()
jameshwart lopez
  • 2,993
  • 6
  • 35
  • 65