Skip to content
This repository was archived by the owner on Jan 31, 2020. It is now read-only.
This repository was archived by the owner on Jan 31, 2020. It is now read-only.

Invokable view variable shouldn't be invoked #85

@antiphp

Description

@antiphp

Hi,

when passing an invokable object to the view and trying to access it, the object is being invoked automatically which may not be intended.

// Controller action
public function testAction()
{
    $viewModel = new ViewModel();
    $viewModel->test = new class {
        public function __invoke(array $params) {}
        public function getName() {
            return 'test';
        }
    };
    return $viewModel;
}

// View
echo $this->test->getName();

Expected output:
test

Actual output:
Argument 1 passed to class@anonymous::__invoke() must be of the type array, none given

The reason is here (Zend/View/Variables.php):

public function offsetGet($key)
{
    if (!$this->offsetExists($key)) {
        if ($this->isStrict()) {
            trigger_error(sprintf(
                'View variable "%s" does not exist',
                $key
            ), E_USER_NOTICE);
        }
        return;
    }

    $return = parent::offsetGet($key);

    // If we have a closure/functor, invoke it, and return its return value
    if (is_object($return) && is_callable($return)) {
        $return = call_user_func($return);
    }

    return $return;
}

The process of passing and accessing variables should not take care of the kind of the variables passed.

I really don't get the point of invoking them automatically. If someone needs automatic invocation we have view helpers. My suggestion is to remove the automatic invocation or if you can't let go, add an interface check.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions