Skip to content

Instantly share code, notes, and snippets.

@dj1020
Created July 4, 2016 03:02
Show Gist options
  • Save dj1020/1959b9dba22d734bfea2e0d3d438fc31 to your computer and use it in GitHub Desktop.
Save dj1020/1959b9dba22d734bfea2e0d3d438fc31 to your computer and use it in GitHub Desktop.
分享一個「用 Closure 取得 Class Private Property」的特殊技巧
<?php
// 用 Closure 取得 Class Private Property
//
// ref: https://ocramius.github.io/blog/accessing-private-php-class-members-without-reflection/
// 比用 reflection 快很多
class Example {
private $myName;
public function __construct($name) {
$this->myName = $name;
}
}
$ex = new Example('Ken Lin');
$reader = function () { return $this->myName; };
$getMyName = $reader->bindTo($ex, $ex);
echo $getMyName() . PHP_EOL; // 輸出:Ken Lin
// 也可以包成一個 helper function
function getProperty($instance, $property) {
$value = Closure::bind(function () use ($property) {
return $this->$property;
}, $instance, $instance)->__invoke();
return $value;
}
echo getProperty($ex, 'myName') . PHP_EOL; // 輸出:Ken Lin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment