Skip to content

Extending class with unnamed type is possible???? #17237

@gzhegow1991

Description

@gzhegow1991

Description

The following code:

<?php

class Hello1
{
	public function helloFn(int $test = 123) // could be any int|string, not work with array|\stdClass
	{
		echo $test . PHP_EOL;
	}
}

class Hello2 extends Hello1
{
	public function helloFn($test = 'tmp')
	{
		echo $test . PHP_EOL;
	}
}

class Hello3 extends Hello2
{
	public function helloFn($test = 456)
	{
		echo $test . PHP_EOL;
	}
}

$tmp = new Hello1();
$tmp->helloFn(); // 123 (int)

$tmp = new Hello2();
$tmp->helloFn(); // tmp (string)

$tmp = new Hello3();
$tmp->helloFn(); // 456 (int)

Resulted in this output:

123
tmp
456

But I expected this output instead:

123
RuntimeException('Signature should be compatible')

PHP Version

PHP 8.0

Operating System

Win10 x64

Please explain why "removing type" is a "feature" not a "bug"

Seems its useful but conflicts with "change type is fatal".
Guess it shouldn't be fixed, but...

ADDED (works as expected, instead of example above):

class Hello1
{
	public function helloFn($test = 123)
	{
		echo $test . PHP_EOL;
	}
}

class Hello2 extends Hello1
{
	public function helloFn(int $test = 456)
	{
		echo $test . PHP_EOL;
	}
}

class Hello3 extends Hello2
{
	public function helloFn($test = 'tmp')
	{
		echo $test . PHP_EOL;
	}
}

Fatal error: Declaration of Hello2::helloFn(int $test = 456) must be compatible with Hello1::helloFn($test = 123) in /home/user/scripts/code.php on line 13

I think - criteria could become more stronger, so "adding type if missing" is allowed, changing or removing, casting is not allowed. Using extended types of previously declared have to be allowed too.

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