php / php/doc-en

`self` doesn't work as expected in combination with late static binding

Open
#3,293 10 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Category: Engine
Dominant language
XML
Stars
596
Forks
890
Avg merge
1d 15h
Merged PRs (30d)
55

Description

Description

The following code:

<?php
class foo {
    static public function getclass() {
        var_dump(get_called_class());
    }
    static public function test() {
        self::getclass();
    }
}

class bar extends foo {}

bar::test();

Resulted in this output:

string(3) "bar"

But I expected this output instead:

string(3) "foo"

Additional context

In the docs about late static binding it says

Static references to the current class like self:: or __CLASS__ are resolved using the class in which the function belongs, as in where it was defined

This leads me to believe that get_called_class() should be returning foo, because that is the class where the self:: was defined, and get_called_class() is called downstream from that.

It's possible that everything's working as it's supposed to, but in that case I believe the documentation for late static binding needs to be updated to include this edge case as it's extremely unintuitive - it feels like self is just a synonym for static in this scenario.

PHP Version

PHP 8.1.27

Operating System

No response

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the late static bindings documentation page linked in the issue and reproduce the provided PHP example to confirm the observed behavior. Review the existing wording around self::, CLASS, and get_called_class(); done means the page clearly explains this edge case or corrects the misleading statement, with an appropriate documentation test or review if the repository provides one.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.