Re: [PHP-DEV] Class cast

This is only part of a thread. view whole thread
  109316
March 26, 2020 01:32 david.proweb@gmail.com (David Rodrigues)
Hello!

> What's wrong with new Number(123)?
Actually it is a simplest case, where only a single information was considered. But you can expand it to something more complex, where currently you will need create a static method to copy the data, which is not a normalized way like cast could do.
> Not sure why would you want to do this? What's the use case?
You could mix the previous answer when arguments to a method that expects a Number, for instance: X::test((Number) $x). Or you can increase the type of information when possible. For instance: function requiresB(B $b); But you have only A $a. You can create: function __cast($value) { if ($value instanceof A) return B($value, 123, M_PI); } Then use: requiresB((B) $a); Atenciosamente, David Rodrigues Em qua., 25 de mar. de 2020 às 20:06, Stanislav Malyshev < smalyshev@gmail.com> escreveu:
> Hi! > > > 1. Converting from A to B: > > > > $a = 123; > > $b = (Number) $a; // $b is now instanceof Number > > > > A instanceof Number will created based on $a value. > > What's wrong with new Number(123)? > > > 2. Reduce object type (I don't know the technical term): > > > > class A {} > > class B extends A {} > > > > $b = new B; > > $a = (A) $b; > > > > $a still is $b, but with "limited" access to A methods and properties. > > Not sure why would you want to do this? What's the use case? > -- > Stas Malyshev > smalyshev@gmail.com >
  109322
March 26, 2020 06:20 smalyshev@gmail.com (Stanislav Malyshev)
Hi!

> Actually it is a simplest case, where only a single information was > considered. But you can expand it to something more complex, where > currently you will need create a static method to copy the data, which > is not a normalized way like cast could do.
You can always use anonymous functions if callable is needed.
> > Or you can increase the type of information when possible. For instance: > > function requiresB(B $b); > > But you have only A $a. > > You can create: > > function __cast($value) { >     if ($value instanceof A) return B($value, 123, M_PI); > }
That's not a cast. That's creating new object from another object. Things like this should be an explicit call. Otherwise the meaning of this code is unclear - it pretends that you just change the type, but in fact it's a completely new object which can be entirely unrelated to the old one. Things like that should be explicit. -- Stas Malyshev smalyshev@gmail.com