Прошло много времени с тех пор, как я работал с PHP, и мне трудно понять, как вызвать $this
из экземпляра класса va ReflectionMethod
Я создаю экземпляр MyClass
и хочу увидеть некоторые переменные, а затем получить доступ к этим переменным из подкласса.
$foo = new MyClass('bootstrap');
$foo->bar = 'baz',
class MyClass {
public $bar = false;
function __construct($wrapper = '')
{
# determine our field wrapper and CSS classes
if (!$wrapper) {
# no wrapper, default divs and css
$this->wrapper = '';
} else {
# user-defined wrapper
$this->wrapper = strtolower($wrapper);
$wrapper_css = $wrapper . '_css';
}
if (!$this->wrapper || in_array($this->wrapper, $this->default_wrapper_types)) {
# use default css
$this->controls = Wrapper::css_defaults();
} else {
# custom wrapper/control types
try {
# check the Controls class for the supplied method
$method = new ReflectionMethod('wrapper::' . $wrapper_css);
if ($method->isStatic()) {
$this->controls = Wrapper::$wrapper_css();
}
} catch (ReflectionException $e) {
# method does not exist, spit out error and set default controls
echo '<span style="color:red">' . $e->getMessage() . '</span>';
$this->controls = Wrapper::css_defaults();
}
}
}
}
class Wrapper extends MyClass {
public static function css_defaults() {
// class names go here...
}
public static function bootstrap_css($key = '') {
// Bootstrap css classes go here...
}
public function bootstrap($element = '', $data = '') {
// Bootstrap form group codes go here...
// $this->bar is not available
var_dump($this->bar);
}
}
Я понимаю, что создаю экземпляр класса и устанавливаю оболочку перед установкой $foo->bar
, поэтому япопытался создать другой метод вместо использования конструктора для установки оболочки, но все равно не может получить доступ $this->bar
// create the wrapper method...
class MyClass {
public $bar = false;
function wrapper($wrapper = '')
{
# determine our field wrapper and CSS classes
if (!$wrapper) {
# no wrapper, default divs and css
$this->wrapper = '';
} else {
# user-defined wrapper
$this->wrapper = strtolower($wrapper);
$wrapper_css = $wrapper . '_css';
}
if (!$this->wrapper || in_array($this->wrapper, $this->default_wrapper_types)) {
# use default css
$this->controls = Wrapper::css_defaults();
} else {
# custom wrapper/control types
try {
# check the Controls class for the supplied method
$method = new ReflectionMethod('wrapper::' . $wrapper_css);
if ($method->isStatic()) {
$this->controls = Wrapper::$wrapper_css();
}
} catch (ReflectionException $e) {
# method does not exist, spit out error and set default controls
echo '<span style="color:red">' . $e->getMessage() . '</span>';
$this->controls = Wrapper::css_defaults();
}
}
}
}
// call it...
$foo = new MyClass();
$foo->bar = 'baz',
$foo->wrapper('bootstrap')
Как я могу это сделать?