Created
January 19, 2022 20:38
-
-
Save stefanofago73/899d89cd0983e214b4533312e9cd6dc9 to your computer and use it in GitHub Desktop.
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 declare(strict_types = 1); | |
//------------------------------------------- | |
// | |
// FIRST NAMESPACES | |
// | |
//------------------------------------------- | |
namespace FST{ | |
echo "in namespace : ".__NAMESPACE__.PHP_EOL; | |
class Pippo | |
{ | |
protected int $value = 10; | |
private final function __construct() | |
{ | |
} | |
protected static function create():static | |
{ | |
return new static(); | |
} | |
function hello():void | |
{ | |
echo "inside Pippo : HELLO!".PHP_EOL; | |
} | |
function value():int | |
{ | |
return $this->value; | |
} | |
} | |
} | |
//------------------------------------------- | |
// | |
// SECOND NAMESPACES | |
// | |
//------------------------------------------- | |
namespace SND{ | |
use FST\Pippo; | |
echo "in namespace : ".__NAMESPACE__.PHP_EOL; | |
class Pluto extends Pippo | |
{ | |
protected static function create():static | |
{ | |
/** @var static $result **/ $result = parent::create(); | |
$result->value=20; | |
return $result; | |
} | |
function hello():void | |
{ | |
echo "inside Pluto (extension of Pippo) HULLO!".PHP_EOL; | |
} | |
function modified():int | |
{ | |
return $this->value+10; | |
} | |
} | |
} | |
//------------------------------------------- | |
// | |
// GLOBAL NAMESPACES | |
// | |
//------------------------------------------- | |
namespace{ | |
use FST\Pippo; | |
use SND\Pluto; | |
echo "in namespace : ".__NAMESPACE__.PHP_EOL; | |
/** | |
* @template T | |
* @param class-string<T> $clazz | |
* @return T | |
* @throw \RuntimeException | |
*/ | |
function create(string $clazz):mixed | |
{ | |
echo "creating a $clazz".PHP_EOL; | |
/** @var \Closure():T|false $result */ | |
$result = \Closure::bind( | |
function() use ($clazz) | |
{ | |
/** @var callable():T $cTor */ | |
$cTor = [$clazz,'create']; | |
return $cTor(); | |
}, | |
NULL, | |
$clazz); | |
if($result !== false){ | |
return $result(); | |
} | |
throw new \RuntimeException("can't create $clazz!"); | |
} | |
$pippo = create(Pippo::class); | |
$pippo->hello(); | |
$pluto = create(Pluto::class); | |
$pluto->hello(); | |
echo var_export($pippo,true).PHP_EOL; | |
echo var_export($pluto,true).PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment