Skip to content

Instantly share code, notes, and snippets.

@tobiassjosten
Created October 15, 2012 14:45
Show Gist options
  • Save tobiassjosten/3892865 to your computer and use it in GitHub Desktop.
Save tobiassjosten/3892865 to your computer and use it in GitHub Desktop.
phpwtf-constmember
<?php
class Holder
{
const myConstant = 'Stabil';
}
class Wrapper
{
public $holder;
public function __construct(Holder $holder)
{
$this->holder = $holder;
}
}
$holder = new Holder();
$wrapper = new Wrapper($holder);
echo $holder::myConstant;
// 'Stabil'
$holder2 = $wrapper->holder;
echo $holder2::myConstant;
// 'Stabil'
echo $wrapper->holder::myConstant;
// PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting
// ',' or ';' in /home/tobias/phpwtf.php on line 24
@ain
Copy link

ain commented Oct 15, 2012

I'd think that at the point where the scope resolution operator kicks in, the reference to the Holder class is not yet in the memory (resolved) and thus fails.

I'd not go with the solution in the above comment, casting is expensive. It indeed works though.

@tobiassjosten
Copy link
Author

@beryllium Haha. Yup, that works. Though I'll stick with $handler = $wrapper->handler; echo $handler::myConstant.

@ain So would you say it's a bug?

@ain
Copy link

ain commented Oct 16, 2012

On a 2nd thought, I think it's just a generic syntax failure. It's a bug I think, a friend of mine reminded about the similar historic PHP 4 quirk where the following code failed too:

class MyClass
{
    function myMethod()
    {
        return true;
    }
}

$arr = array();
$arr[] = new MyClass();
$res = $arr[0]->myMethod();

so you always had to use the method over the previously defined reference.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment