<?php
class StringLib
{
// This should be Container not library variable..
// But for tests is fine..
static $lib;
public function __construct($lib)
{
return $this->testChangeLib($lib);
}
// Method just for tests
public static function testChangeLibStatic( $lib )
{
$className = $lib . get_called_class();
if( class_exists( $className ))
{
static::$lib = new $className;
}
}
// Method just for tests
public function testChangeLib( $lib ) : StringLib
{
$className = $lib . get_called_class();
if( class_exists( $className ))
{
static::$lib = new $className;
return $this;
}
}
public function __call( string $method, array $args = [])
{
if( method_exists(static::$lib, $method))
{
return call_user_func_array( array(static::$lib, $method), $args);
}
}
public static function __callStatic( string $method, array $args = [])
{
if( method_exists(static::$lib, $method))
{
return call_user_func_array(array(static::$lib, $method), $args);
}
}
}
interface StringInterface
{
public function strlen( string $string) : int;
}
class PHPStringLib implements StringInterface
{
public function strlen( string $string) : int
{
return strlen($string);
}
}
class MBStringLib implements StringInterface
{
// This File may have error trigger if MB is disabled
// This should be configurable
static $charset = 'UTF-8';
public function strlen( string $string) : int
{
return mb_strlen( $string, self::$charset);
}
}
class CustomStringLib
{
public function strlen($string) : int
{
// Just another way which again uses str_ function..
return count(str_split($string));
}
}
$teststring = 'One two три';
$test = new StringLib( 'MB' );
echo "\n" . $test->strlen( $teststring ) . "\n";
$test->testChangeLib( 'PHP' );
echo "\n" . $test->strlen( $teststring ) . "\n";
$test->testChangeLib( 'Custom' );
echo "\n" . $test->strlen( $teststring ) . "\n";
StringLib::testChangeLibStatic('MB');
echo "\n" . StringLib::strlen( $teststring ) . "\n";
StringLib::testChangeLibStatic('PHP');
echo "\n" . StringLib::strlen( $teststring ) . "\n";
StringLib::testChangeLibStatic('Custom');
echo "\n" . StringLib::strlen( $teststring ) . "\n";