Skip to content

Question about redefining public or protected properties. #16296

@geniuszxy

Description

@geniuszxy

Description

Why does PHP allow redefining (redeclaring) a public or protected property with the same name in a derived class without hiding the corresponding property in the base class? In C++, equivalent code will output the expected result. So is this a bug? If not, what is the significance of allowing this?

https://3v4l.org/JfJOY

The following code:

<?php
class Base
{
	private int $pv = 0;
	protected int $pt = 0;
	public int $pb = 0;
	public function setBase(int $i) { $this->pv = $i; $this->pt = $i; $this->pb = $i; }
	public function dump() { echo "private(base):$this->pv; protected(base):$this->pt; public(base):$this->pb\n"; }
};

class Derived extends Base
{
	private int $pv = 0;
	protected int $pt = 0;
	public int $pb = 0;
	public function setDerived(int $i) { $this->pv = $i; $this->pt = $i; $this->pb = $i; }
	public function dump() { parent::dump(); echo "private(derived):$this->pv; protected(derived):$this->pt; public(derived):$this->pb\n"; }
};

$o = new Derived;
$o->setBase(2);
$o->dump();
$o->setDerived(6);
$o->dump();

Resulted in this output:

private(base):2; protected(base):2; public(base):2
private(derived):0; protected(derived):2; public(derived):2
private(base):2; protected(base):6; public(base):6
private(derived):6; protected(derived):6; public(derived):6

But I expected this output instead:

private(base):2; protected(base):2; public(base):2
private(derived):0; protected(derived):0; public(derived):0
private(base):2; protected(base):2; public(base):2
private(derived):6; protected(derived):6; public(derived):6

PHP Version

8.3.12

Operating System

No response

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