3v4l.org

run code in 300+ PHP versions simultaneously
<?php class DataMapper { /** * @var array */ private $rawData; /** * @var array */ private $parsedData; /** * @var array */ private $mapping = [ 'dbField1' => 'outputField1', 'dbField2' => ['outputField2' => ['double']], 'dbField3' => ['outputField3' => ['double', 'dollars']] ]; public function __construct(array $data) { $this->rawData = $data; $this->mapData(); } /** * @param $value * @return mixed */ private function double($value) { return $value * 2; } /** * @param $value * @return string */ private function dollars($value) { return $value . "$"; } // Yes, I know the methods shouldn't be here but it rather be decoupled in another class and // injected with a DI but I wrote it like this just as an example private function mapData() { foreach($this->mapping as $dbFieldName => $content) { if(isset($this->rawData[$dbFieldName])) { if(is_string($content)) { $this->parsedData[$content] = $this->rawData[$dbFieldName]; } else if (is_array($content)) { $frontFieldName = key($content); $functionsArray = reset($content); $value = $this->rawData[$dbFieldName]; foreach($functionsArray as $functionName) { $value = $this->{$functionName}($value); } $this->parsedData[$frontFieldName] = $value; } } } } /** * Simple getter * @return array */ public function getParsedData() { return $this->parsedData; } } // Usually the data comes from the DB so it would be in some kind of Row Set structure $data = ['dbField1' => 1, 'dbField2' => 1, 'dbField3' => 1]; // The data is handed to the Holder which parses it $dm = new DataMapper($data); // The data is parsed so it can be echo json_encode($dm->getParsedData());
Output for 5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.27, 8.2.0 - 8.2.17, 8.3.0 - 8.3.4
{"outputField1":1,"outputField2":2,"outputField3":"2$"}
Output for 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29
Parse error: syntax error, unexpected '[' in /in/U0QQs on line 16
Process exited with code 255.
Output for 5.0.0 - 5.0.5
Parse error: parse error, unexpected '[' in /in/U0QQs on line 16
Process exited with code 255.
Output for 4.4.2 - 4.4.9
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /in/U0QQs on line 6
Process exited with code 255.
Output for 4.3.0 - 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1
Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /in/U0QQs on line 6
Process exited with code 255.
Output for 4.3.2 - 4.3.4
Parse error: parse error, expecting `T_OLD_FUNCTION' or `T_FUNCTION' or `T_VAR' or `'}'' in /in/U0QQs on line 6
Process exited with code 255.

preferences:
204.6 ms | 401 KiB | 393 Q