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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With