Skip to content

Instantly share code, notes, and snippets.

@sv3tli0 sv3tli0/stringlibphp7.php Secret
Created Sep 10, 2015

Embed
What would you like to do?
Example of string lib + interface and subclasses
<?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
You can’t perform that action at this time.