Как я могу получить доступ к $ this из подкласса, называемого через ReflectionMethod? - PullRequest
1 голос
/ 04 июня 2019

Прошло много времени с тех пор, как я работал с 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')

Как я могу это сделать?

1 Ответ

0 голосов
/ 06 июня 2019

Вы не можете получить доступ к переменной экземпляра в статическом методе.Тем не менее, вы можете передать экземпляр в параметры вашего метода или передать значение в качестве параметра следующим образом:

public static function css_defaults($instance)
{
    echo $instance->bar; // baz
}

И вызвать его так:

Wrapper::css_defaults($this);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...