On 26/08/2024 10:03, Andreas Leathley wrote:
On 24.08.24 18:49, Bilge wrote:
For me there is another question. When using interfaces and classes,
default values can be introduced, like this:
interface CompressionInterface
{
public function compress(string $data, int $level): string;
}
class GzipCompression implements CompressionInterface
{
public function compress(string $data, int $level = 4): string
{
// do something
}
}
When I have the GzipCompression class, I would know there is a default
value for $level, but when using the interface there might or might not
be a default value, depending on the implementation. As far as I read
the RFC, using "default" when there is no default would lead to a
runtime exception, but there is no way of finding out if there is a
default if you do not already know. Being able to test that could be
useful, although I am not sure about the syntax for that. In the example
when getting CompressionInterface, I might test for the existence of a
default value of $level and leave it at the default if there is a
default (maybe I know that some implementations have a default value,
others don't). One could test the specific implementation with
instanceof checks, but the advantage of "default" could be that you do
not need to know the implementation and could only adapt to possibly
defined default values.
Hi Andreas,
Thanks for this question; I find this super interesting because it's
something we haven't thought about yet. I must admit I completely
overlooked that, whilst an interface /can/ require implementers to
specify a default, in the case that they do not, it is still valid for
implementations to selectively elect to provide one. Therefore I can
append to your example the following case (I removed the `string` return
type for now):
class ZipCompression implements CompressionInterface
{
public function compress(string $data, int $level)
{
var_dump($level);
}
}
new GzipCompression()->compress('', default ?? 6);
new ZipCompression()->compress('', default ?? 6);
In this case, we get the following output:
int(4)
Fatal error: Uncaught ValueError: Cannot pass default to required
parameter 2 of ZipCompression::compress()
I would like to fix this if possible, because I think this should be
valid, with emphasis on /if possible/, because it may be prohibitively
complex. Will update later.
Cheers,
Bilge