Created
December 8, 2022 04:54
-
-
Save fumikito/21d76ac94e59fc51c428c2d65125d42c to your computer and use it in GitHub Desktop.
1つのtraitを利用する2つのtraitがあり、それを1つのクラスで実装した場合の変数の扱い
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait BaseTrait { | |
private $counter = 0; | |
private $greeting = 'Hello World!'; | |
public function say_hello() { | |
$this->counter++; | |
echo $this->greeting . PHP_EOL; | |
} | |
public function greet_count() { | |
printf( 'Greeted %d times' . PHP_EOL, $this->counter ); | |
} | |
} | |
trait John { | |
use BaseTrait; | |
public function john() { | |
echo 'Hi, john. '; | |
$this->say_hello(); | |
} | |
} | |
trait Lisa { | |
use BaseTrait; | |
public function lisa() { | |
echo 'Hi, Lisa! '; | |
$this->say_hello(); | |
} | |
} | |
class Me { | |
use John, Lisa; | |
public function greet() { | |
$this->john(); | |
$this->lisa(); | |
$this->greet_count(); | |
} | |
} | |
$me = new Me(); | |
$me->greet(); | |
// ここで$countは2になっているべき |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment