Last active
September 2, 2022 14:44
-
-
Save cameronjacobson/b864ea462e7ea64e6c77 to your computer and use it in GitHub Desktop.
PHP Late Static Binding - example
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 | |
abstract class GenericParser | |
{ | |
abstract public static function getTokens(); | |
public function convertTextToArray($data){ | |
$tokens = static::getTokens(); | |
return array_map(function($line) use ($tokens) { | |
return array_map(function($col) use ($tokens) { | |
return trim($col, $tokens['enclosed_char']); | |
}, explode($tokens['separator'], $line)); | |
}, explode($tokens['eol'], $data)); | |
} | |
} | |
class CSVParser extends GenericParser | |
{ | |
public static function getTokens(){ | |
return array( | |
'eol'=>"\n", | |
'separator'=>",", | |
'enclosed_char'=>'"' | |
); | |
} | |
} | |
class TSVParser extends GenericParser | |
{ | |
public static function getTokens(){ | |
return array( | |
'eol'=>"\n", | |
'separator'=>"\t", | |
'enclosed_char'=>"'" | |
); | |
} | |
} | |
$csvParser = new CSVParser(); | |
print_r($csvParser->convertTextToArray(<<<TEXT | |
"a","b","c" | |
"1","2","3" | |
TEXT | |
)); | |
$tsvParser = new TSVParser(); | |
print_r($tsvParser->convertTextToArray("'a'\t'b'\t'c' | |
'1'\t'2'\t'3'")); | |
/* | |
OUTPUT: | |
Array | |
( | |
[0] => Array | |
( | |
[0] => a | |
[1] => b | |
[2] => c | |
) | |
[1] => Array | |
( | |
[0] => 1 | |
[1] => 2 | |
[2] => 3 | |
) | |
) | |
Array | |
( | |
[0] => Array | |
( | |
[0] => a | |
[1] => b | |
[2] => c | |
) | |
[1] => Array | |
( | |
[0] => 1 | |
[1] => 2 | |
[2] => 3 | |
) | |
) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment