Last active
July 21, 2018 06:04
-
-
Save msankhala/4c1aa4f693e57e0213e3a78c8be9b483 to your computer and use it in GitHub Desktop.
Trait and static method.
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 | |
/** | |
* FileGenerator. | |
*/ | |
trait FileGeneratorTrait | |
{ | |
public static function generateFile() { | |
echo "generating file \n"; | |
} | |
} | |
class MyClass { | |
use FileGeneratorTrait; | |
public function create() { | |
// In class's method trait's STATIC method can be accessed with self:: and $this. | |
self::generateFile(); | |
$this->generateFile(); | |
} | |
} | |
$obj = new MyClass(); | |
$obj->create(); | |
//output: | |
//generating file | |
// generating file | |
trait ImageGeneratorTrait { | |
protected $messenger; | |
protected static $painter; | |
public function messenger() { | |
$this->messenger = 'Here'; | |
echo $this->messenger; | |
} | |
public static function painter() { | |
self::$painter = 'My painter'; | |
echo self::$painter; | |
} | |
} | |
class ImageGenerator { | |
use ImageGeneratorTrait; | |
public static function generate() { | |
// In class's STATIC method trait's method can't be accessed with $this. | |
$this->messenger(); // This will throw error. | |
} | |
public static function paint() { | |
// In class's STATIC method trait's STATIC method can't be accessed with self. | |
self::painter(); | |
} | |
} | |
$o = new ImageGenerator(); | |
// ImageGenerator::generate(); | |
ImageGenerator::paint(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment