Skip to content

Instantly share code, notes, and snippets.

@sochi
Created March 14, 2021 16:41
Show Gist options
  • Save sochi/237f8ab43ef3e63d767a1c703208c1f3 to your computer and use it in GitHub Desktop.
Save sochi/237f8ab43ef3e63d767a1c703208c1f3 to your computer and use it in GitHub Desktop.
<?php
namespace App\Model;
class ToStringObject {
private $data;
private $primaryKey;
public function __construct(array $data, string $primaryKey) {
$this->data = $data;
if (!array_key_exists($primaryKey, $data)) {
throw new \ValueException('Primary key is not in data');
}
$this->primaryKey = $primaryKey;
}
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
public function __isset($name) {
return isset($this->data[$name]);
}
public function __unset($name) {
unset($this->data[$name]);
}
public function __toString() {
return (string) $this->data[$this->primaryKey];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment