Skip to content

Instantly share code, notes, and snippets.

@fumikito
Created December 8, 2022 04:54
Show Gist options
  • Save fumikito/21d76ac94e59fc51c428c2d65125d42c to your computer and use it in GitHub Desktop.
Save fumikito/21d76ac94e59fc51c428c2d65125d42c to your computer and use it in GitHub Desktop.
1つのtraitを利用する2つのtraitがあり、それを1つのクラスで実装した場合の変数の扱い
<?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