Skip to content

Redeclaring protected properties on children creates a liskov violation #19406

Closed as duplicate

Description

@jnvsor

Description

The following code:

<?php
class P {
    protected $v;
}

class C extends P {
    public function test(P $i) {
        return $i->v;
    }
}

class C2 extends P {
    protected $v;
}

$c = new C;
$c2 = new C2;
$c->test($c2);

Resulted in this output:

PHP Fatal error:  Uncaught Error: Cannot access protected property C2::$v

But I expected this output instead:


After a discussion on the mailing list everyone seemed to agree it's a bug, and I believe fixing it wouldn't break any pre-existing code. Properties were invariant up to 8.4, and property hook variance is well defined.

PHP Version

PHP 8.4.10 (cli) (built: Jul  3 2025 12:35:27) (NTS)
Copyright (c) The PHP Group
Built by Debian
Zend Engine v4.4.10, Copyright (c) Zend Technologies
    with Zend OPcache v8.4.10, Copyright (c), by Zend Technologies
    with Xdebug v3.4.3, Copyright (c) 2002-2025, by Derick Rethans

Operating System

No response

Activity

  1. alecpl commented on Aug 10, 2025

    @alecpl

    I don't really know Liskov, but you're accessing a protected property from outside. The fact that C extends P has nothing to do with this. How this is a bug?

  2. alecpl commented on Aug 10, 2025

    @alecpl

    OK, I saw the attached PR. I think I understand now. And I don't agree.

  3. iluuu1994 commented on Aug 15, 2025

    @iluuu1994
    Member

    @alecpl The properties are related because of their shared parent property. Methods work the same way. You can call protected methods that are overridden in sibling classes.

    @jnvsor Can you try PHP 8.4.12 RC1? It should be solved there by #19046. It should be released in ~2 weeks.

  4. jnvsor commented on Aug 15, 2025

    @jnvsor
    Author

    Thanks @iluuu1994 -- Tested with docker run -it php:8.4.12RC1-zts-bookworm php -a and it doesn't throw an error any more

  5. iluuu1994 commented on Aug 15, 2025

    @iluuu1994
    Member

    @jnvsor Thanks for testing!

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions