Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor default non optional parameters initializes objects?

Tags:

php

laravel

I have trouble understanding the type hinting and initializing of arguments in the constructor. I stumbled across this code:

class TabController {
    protected $post;
    protected $user;
    public function __construct(Post $post, User $user)
    {
        $this->post = $post;
        $this->user = $user;
    }
}

I thought that arguments wasn't optional if it wasn't set up like this:

public function __construct(Post $post=NULL, User $user=NULL)

It seems both these examples initializes an empty object (not NULL).

If I try the first example in a normal function it fails if I dont supply the arguments.

like image 415
The Silencer Avatar asked Feb 10 '26 16:02

The Silencer


1 Answers

First, type hinting. It is intended for verification input data. For example:

class User {
    protected $city;
    public function __construct(City $city) {
        $this->city = $city;
    }
}
class City {}
class Country {}
$city = new City(); $user = new User($city); //all ok
$country = new Country(); $user = new User($country); //throw a catchable fatal error

Second, initializing an empty object. This is done as follows:

class User {
    protected $city;
    public function __construct(City $city = null) {
        if (empty($city)) { $city = new City(); }
        $this->city = $city;
    }
}
like image 183
Aleksandr Khristenko Avatar answered Feb 14 '26 13:02

Aleksandr Khristenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!