Last active
April 11, 2019 07:34
-
-
Save arieffikhrie/4af69b60baad38c111a626de9145d270 to your computer and use it in GitHub Desktop.
dynamic method name for class
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 Test { | |
private $data = [ | |
'first' => 1, | |
'second' => 2, | |
'third' => 3, | |
'hundredTH' => 100, | |
'5Fifth' => 5 // following method rules, method never start with a digit, so this will return false | |
]; | |
public function __call($name, $arguments) { | |
$pattern = '/^get(?!\d.+$)([a-zA-Z0-9]+$)/'; | |
$matches = []; | |
preg_match($pattern, $name, $matches); | |
if (count($matches) === 0) { | |
return false; | |
} | |
if (!isset($matches[1]) || empty($matches[1])) { | |
return false; | |
} | |
// The function itself is case sentitive, only converting the first camel case to be small letter, | |
// only the implication would be, the data key start with 'First', then getFirst() will always | |
// get data from key 'first' instead of 'First' | |
$keyName = lcfirst($matches[1]); | |
if (!isset($this->data[$keyName]) || empty($this->data[$keyName])) { | |
return false; | |
} | |
return $this->data[$keyName]; | |
} | |
} | |
$test = new Test(); | |
var_dump($test->getFirst()); | |
var_dump($test->getSecond()); | |
var_dump($test->getFifth()); // the key does not exist in $data | |
var_dump($test->gethundredTH()); // this return 100 | |
var_dump($test->gethundredth()); // return false | |
var_dump($test->get5Fifth()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment