Skip to content

Commit 003bb06

Browse files
committed
Use PHP constructor property promotion
1 parent 6513260 commit 003bb06

File tree

3 files changed

+6
-12
lines changed

3 files changed

+6
-12
lines changed

_posts/06-02-01-Basic-Concept.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,16 @@ class MysqlAdapter {}
2929
{% endhighlight %}
3030

3131
This code can be refactored to use Dependency Injection and therefore loosen the dependency.
32+
Here, we inject the dependency in a constructor and use the [constructor property promotion][php-constructor-promotion] so it is available as a property across the class:
3233

3334
{% highlight php %}
3435
<?php
3536
namespace Database;
3637
3738
class Database
3839
{
39-
protected $adapter;
40-
41-
public function __construct(MySqlAdapter $adapter)
40+
public function __construct(protected MySqlAdapter $adapter)
4241
{
43-
$this->adapter = $adapter;
4442
}
4543
}
4644
@@ -50,3 +48,5 @@ class MysqlAdapter {}
5048
Now we are giving the `Database` class its dependency rather than creating it itself. We could even create a method
5149
that would accept an argument of the dependency and set it that way, or if the `$adapter` property was `public` we
5250
could set it directly.
51+
52+
[php-constructor-promotion]: https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon.constructor.promotion

_posts/06-03-01-Complex-Problem.md

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,11 +82,8 @@ namespace Database;
8282
8383
class Database
8484
{
85-
protected $adapter;
86-
87-
public function __construct(AdapterInterface $adapter)
85+
public function __construct(protected AdapterInterface $adapter)
8886
{
89-
$this->adapter = $adapter;
9087
}
9188
}
9289

_posts/07-04-01-Interacting-via-Code.md

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,8 @@ include 'views/foo-list.php';
7070
<?php
7171
class FooModel
7272
{
73-
protected $db;
74-
75-
public function __construct(PDO $db)
73+
public function __construct(protected PDO $db)
7674
{
77-
$this->db = $db;
7875
}
7976
8077
public function getAllFoos() {

0 commit comments

Comments
 (0)