[php-src] Issue #11249: When calling a parent class's static method using call_user_func(), static::class return the child class

From: Date: Tue, 16 May 2023 09:39:30 +0000
Subject: [php-src] Issue #11249: When calling a parent class's static method using call_user_func(), static::class return the child class
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-244458@lists.php.net to get a copy of this message
Issue: https://github.com/php/php-src/issues/11249
Author: takyam-git

### Description

The following code:

```php
<?php

class ParentClass
{
    public static function whoAmI(): void
    {
        var_dump(static::class);
    }
}

class ChildClass extends ParentClass
{
    public function byCallUserFunc(): void
    {
        call_user_func([\ParentClass::class, "whoAmI"]);
    }

    public function bySyntaxCall(): void
    {
        $className = ParentClass::class;
        $className::whoAmI();
    }

    public function directCall(): void
    {
        ParentClass::whoAmI();
    }

    public function callSelf(): void
    {
        self::whoAmI();
    }
}

echo "ParentClass::whoAmI()" . PHP_EOL;
ParentClass::whoAmI();

echo PHP_EOL . 'call_user_func([\ParentClass::class, "whoAmI"])' . PHP_EOL;
call_user_func([\ParentClass::class, "whoAmI"]);

$child = new ChildClass();
echo PHP_EOL . 'call_user_func([\ParentClass::class, "whoAmI"]) on ChildClass' .
PHP_EOL;
$child->byCallUserFunc();

echo PHP_EOL . '$className::whoAmI()' . PHP_EOL;
$child->bySyntaxCall();

echo PHP_EOL . "ParentClass::whoAmI() on ChildClass" . PHP_EOL;
$child->directCall();

echo PHP_EOL . "self::whoAmI()" . PHP_EOL;
$child->callSelf();
```

Resulted in this output:
```
ParentClass::whoAmI()
string(11) "ParentClass" // OK

call_user_func([\ParentClass::class, "whoAmI"])
string(11) "ParentClass" // OK

call_user_func([\ParentClass::class, "whoAmI"]) on ChildClass
string(10) "ChildClass" // why?

$className::whoAmI()
string(11) "ParentClass" // OK

ParentClass::whoAmI() on ChildClass
string(11) "ParentClass" // OK

self::whoAmI()
string(10) "ChildClass" // OK
```

But I expected this output instead:
```
call_user_func([\ParentClass::class, "whoAmI"]) on ChildClass
string(10) "ParentClass"
```

I am calling a parent class's static method from a child class, as shown in the code. 
In the parent class's static method, I am outputting static::class.

When I call ParentClass::whoAmI() , the name of the parent class
ParentClass is output.
Also, when I call $className::whoAmI() or ParentClass::whoAmI() from the
child class, ParentClass is output as well.

However, when I use call_user_func() , the name of the child class
ChildClass is output.

Only when using `call_user_func() , it behaves in a way that is counterintuitive.

https://3v4l.org/3Vd6E#v8.1.19

### PHP Version

PHP 8.1.16

### Operating System

Mac


Thread (1 message)

  • takyam-git
« previous php.bugs (#244458) next »