Skip to content

Instantly share code, notes, and snippets.

@msankhala
Last active July 21, 2018 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msankhala/4c1aa4f693e57e0213e3a78c8be9b483 to your computer and use it in GitHub Desktop.
Save msankhala/4c1aa4f693e57e0213e3a78c8be9b483 to your computer and use it in GitHub Desktop.
Trait and static method.
<?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