-
-
Save sv3tli0/76ea9e81ee73abcc271d to your computer and use it in GitHub Desktop.
Example of string lib + interface and subclasses
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 | |
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 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"; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment