Re: What about a magic __toArray() method?

From: Date: Tue, 04 Feb 2020 12:55:23 +0000
Subject: Re: What about a magic __toArray() method?
References: 1 2 3 4 5  Groups: php.internals 
Request: Send a blank email to internals+get-108368@lists.php.net to get a copy of this message
Correct: an explicit $foo->toArray() call suffices. For other readers, more about $foo->toArray() vs (array) $foo is described at https://github.com/ShittySoft/symfony-live-berlin-2018-doctrine-tutorial/pull/3#issuecomment-460441229
This is a valid point. Perhaps another problem lies at its base: why can one cast null to a string in PHP? Would it be more appropriate to throw a CastError or similar? Or does casting null to another type make sense in some scenarios? One could go as far as to only allow types that overload the appropriate cast operator to cast to the type without error. This implies the question of how to handle built-in types, such as casting floats to string.
- It is less explicit than choosing a purpose-specific method name
I think it's also important to mention whether this discussion is about explicit casts only, or not - and also about implicit casts, or coercion. "(string) $var" doesn't seem a lot less explicit to me than "$var->toString()", but if it is coerced automatically when being passed to e.g. a function taking a string, that is of course a different story. Coercions and implicit casting using the overloaded operators could perhaps also be limited to non-strict mode, if desired, which is also the case for scalar types currently, IIRC.

« previous php.internals (#108368) next »