PHP code example of chillerlan / php-traits

1. Go to this page and download the library: Download chillerlan/php-traits library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

chillerlan / php-traits example snippets


class MyClass{
	use ClassLoader;
	
	protected function doStuff(string $class){
		$obj = $this->loadClass(__NAMESPACE__.'\\Whatever\\'.$class);
		
		// do stuff
	}
}

class SomeClass implements MyInterface{
	public funtion __construct($param_foo){}
}

class OtherClass implements MyInterface{
	public funtion __construct($param_foo, $param_bar){}
}

class MyClass{
	use ClassLoader;
	
	protected $classes = [
		'foo' => SomeClass::class, 
		'bar' => OtherClass::class
	];
	
	protected funtion initInterface(string $whatever, $foo, $bar = null):MyInterface{
	
		foreach($this->classes as $what => $class){
			if($whatever === $what){
				return $this->loadClass($class, MyInterface::class, $foo, $bar);
			}
		}
	
	}
}

class MyMagicContainer{
	use Magic;

	protected $foo;

	protected function magic_get_foo(){
		// do whatever...
		
		return 'foo: '.$this->foo;
	}

	protected function magic_set_foo($value){
		// do stuff with $value
		// ...
		
		$this->foo = $value.'bar';
	}
}

$magic = new MyMagicContainer;

$magic->foo = 'foo';

var_dump($magic->foo); // -> foo: foobar


class MyEnumerableContainer implements EnumerableInterface{
	use Enumerable;

	public function __construct(array $data){
		$this->array = $data;
	}
}

$enum = new MyEnumerableContainer($data);

$enum
	->__each(function($value, $index){
		// do stuff
		
		$this->array[$index] = $stuff;
	})
	->__reverse()
	->__to_array()
;

$arr = $enum->__map(function($value, $index){
	// do stuff
	
	return $stuff;
});

$enum;

json
{
	": "^7.2",
		"chillerlan/php-traits": "dev-master"
	}
}