php - Specifying that parameter is a database in the constructor -


in following code:

protected $db;      public function __construct(database $db)      {         $this->db = $db;     } 

what point in specifying parameter $db database if can name whatever want , still work?

that's type declaration. manual:

type declarations allow functions require parameters of type @ call time. if given value of incorrect type, error generated: in php 5, recoverable fatal error, while php 7 throw typeerror exception.

to specify type declaration, type name should added before parameter name. declaration can made accept null values if default value of parameter set null.

so, if didn't specify type declaration $db in code, instantiate class null argument, cause object's $db parameter set null:

$object = new classname( null ); 

by specifying single parameter constructor must of type database, php throw error (or exception in php 7) if pass other database object. example:

$object = new classname( null ); // throws error / exception  $db     = new database(); $object = new classname( $db ); // performs expected. 

in particular case, database object type defined framework/library you're working (i.e. class database { ... }).


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -