0

In the following code:

protected $db;

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

What is the point in specifying that the parameter $db is a Database if you can name it whatever you want and it will still work?

5
  • The naming of a variable / property has nothing to do with its type. What would happen if you passed in an object of type Date, for example? Errors would be thrown that methods / properties do not exist. Commented Sep 10, 2017 at 14:26
  • No I mean the Database keyword before the variable name. How do I search about this convention so I can learn more about it? Commented Sep 10, 2017 at 14:30
  • Yes, I know what you mean. That specifies what type the variable $db should be. You're aware that variables in PHP can have different types, right? Commented Sep 10, 2017 at 14:31
  • Yes, int, bool, etc.. but Database? I have seen it named just db and it still works. Commented Sep 10, 2017 at 14:36
  • Please see my answer, it should provide all you need to understand what's going on here. Commented Sep 10, 2017 at 14:37

1 Answer 1

2

That's a type declaration. From the manual:

Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.

To specify a type declaration, the type name should be added before the parameter name. The declaration can be made to accept NULL values if the default value of the parameter is set to NULL.

So, if we didn't specify the type declaration for $db in your code, we could instantiate the class with a null argument, which would cause the object's $db parameter to be set to null:

$object = new ClassName( null );

By specifying that the single parameter for the constructor must be of type Database, PHP will throw an error (or exception in PHP 7) if we pass it anything other than a Database object. For example:

$object = new ClassName( null ); // Throws an error / exception

$db     = new Database();
$object = new ClassName( $db ); // Performs as expected.

In this particular case, Database is an object type defined by the framework/library you're working with (i.e. class Database { ... }).

Sign up to request clarification or add additional context in comments.

1 Comment

I see now. Thank you for the examples, they really helped me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.