Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Using Language constructs in combination with magic methods

Tags:

php

This question made me curious about using language constructs in combination with PHP's magic methods. I have created a demo code:

<?php
class Testing {

    public function scopeList() {
        echo "scopeList";
    }

    public function __call($method, $parameters) {
        if($method == "list") {
            $this->scopeList();
        }
    }

    public static function __callStatic($method, $parameters) {
        $instance = new static;
        call_user_func_array([$instance, $method], $parameters);
    }
}

//Testing::list();
$testing = new Testing();
$testing->list();

Why does Testing::list() throw a syntax error and $testing->list() does not?

Due to php reserved keywords both should fail?

like image 578
shock_gone_wild Avatar asked Dec 18 '15 10:12

shock_gone_wild


2 Answers

Context sensitive identifiers are now supported for PHP 7.0+ and your code would simply work. Updating your PHP would fix the issue.

This was the approved RFC that made the change: https://wiki.php.net/rfc/context_sensitive_lexer.

You can get more information about new features and breaking changes on the following (unofficial) PHP 7 reference: https://github.com/tpunt/PHP7-Reference#loosening-reserved-word-restrictions

like image 173
marcio Avatar answered Oct 26 '22 23:10

marcio


Update PHP 7

PHP 7 addressed the described behaviour and implemented a feature called context sensitive lexer as brought up by marcio.

Your code will simply work with PHP 7.


Situation before PHP 7

Syntax errors are thrown before PHP is even aware of the fact that a method is available through __callStatic(), it happens at parsing stage.

The behaviour you described seems to be a bug in the PHP parser, at least an inconsistency that should be described in the documentation.

I would file a bug report. Good catch!


Update: The OP has file a bug report which can be found here: https://bugs.php.net/bug.php?id=71157

like image 20
hek2mgl Avatar answered Oct 26 '22 23:10

hek2mgl