3v4l.org

run code in 300+ PHP versions simultaneously
<?php trait GetterAndSetter { /** * @var string */ private $setterPrefix = 'set'; /** * @var string */ private $getterPrefix = 'get'; /** * Assigns value to property by attempting to find its * setter. If no setter exists the value is casted into * appropriate type and assigned to the property directly. * * @param $key * @param $value * @return $this */ function __set($key, $value) { $expectedSetter = "{$this->setterPrefix}{$key}"; if ( method_exists($this, $expectedSetter) ) { $this->{$expectedSetter}($value); } elseif ( property_exists($this, $key) ){ $enforcedType = gettype($this->{$key}); $this->{$key} = $value; settype($this->{$key}, $enforcedType); } return $this; } /** * Invokes matching getter if defined * otherwise returns property as is. * * @param $key * @return mixed */ function __get($key) { $expectedGetter = $this->getterPrefix . $key; if ( method_exists($this, $expectedGetter) ) { return $this->{$expectedGetter}(); } return $this->{$key}; } /** * Resolves setClassProperty($val) to $obj->classProperty = $val, * casts appropriate type to value and assigns * to property * * @param $method string Name of possible setter method * @param $val mixed Value to assign to property * @return $this */ function __call($method, $val=[]) { $possibleKey = lcfirst(str_replace($this->setterPrefix, '', $method)); if ( property_exists($this, $possibleKey) ){ $enforcedType = gettype($this->{$possibleKey}); $this->{$possibleKey} = $val[0]; settype($this->{$possibleKey}, $enforcedType); } return $this; } } class AuthorizeNetCustomer { //Will call setters when available otherwise //value will be casted to the property's type //and assigned. use GetterAndSetter; private $merchantCustomerId; private $description; private $email; private $paymentProfiles = array(); private $shipToList = array(); private $customerProfileId; function __construct() { $this->merchantCustomerId = (int) $this->merchantCustomerId; $this->customerProfileId = (int) $this->customerProfileId; $this->description = (string) $this->description; $this->email = (string) $this->email; } public function setPaymentProfiles(array $val){ $this->paymentProfiles = $val; } public function setShipToList(array $val){ $this->shipToList = $val; } public function getShipToList() { return 'adasd'; } } $a = new AuthorizeNetCustomer(); $a->setEmail('cgrandos@delivery.com'); $a->merchantCustomerId = '1'; $a->setCustomerProfileId('34') ->setDescription(232323) ->setShipToList([1,2,3]); var_dump($a->email); var_dump($a->merchantCustomerId); var_dump($a->customerProfileId); var_dump($a->description); var_dump($a->shipToList);

preferences:
52.95 ms | 402 KiB | 5 Q