> On the other hand, I would just use an array. (without any "magic"
> like methods on structs, yes you would have to write plain functions
> and not use OOP like methods).

Yeah, that's what people are doing right now - the problem with that, is
you have the class-name referenced on every call, e.g.:

abstract class Color
{
    public static function create($r, $g, $b)
    {
        return array('r'=>$r, 'g'=>$g, 'b'=>$b);
    }

    public static function mix(array $base, array $mix, $amount)
    {
        return array(
            'r' => $base['r'] * $amount + $mix['r'] * (1 - $amount),
            'g' => $base['g'] * $amount + $mix['g'] * (1 - $amount),
            'b' => $base['b'] * $amount + $mix['b'] * (1 - $amount),
        );
    }
}

$red = Color::create(1, 0, 0);

$green = Color::create(0, 1, 0);

$mix = Color::mix($red, $green, 0.5);

The problem with this approach, is you have a static reference to the
Color-class for every method-call.

With structs you can accomplish the same thing without littering your code
with static class-references.

With pseudo-types implemented as arrays in this way, you also can't hope to
have IDE support or static analysis, e.g. for properties...



On Fri, Apr 5, 2013 at 10:00 AM, ALeX <lists....@tx0.eu> wrote:

> > I imagine the implementation could be something along the lines of
> checking
> > for the '__struct' key when somebody attempts to use method-call syntax
> on
> > an array, invoking the appropriate method with $this referencing the
> array
> > you were using.
> >
> > The rest of the time, a struct, for all intents and purposes, is just an
> > array.
>
> One thing I do not like about the "struct as array" is that you can
> create "invalid" structs, in classes you could have all variables
> private and check during set, but not here: "$array = ['r'=>1,
> 'b'=>'yes', '__struct'=>'Color'];".
>
> Hmm... just an thought: why not make struct almost like a class except
> that $this is a copy (on write) - modifying and returning $this would
> be a new instance of that struct/class. That would give you
> public/private/static/variables/methods/interfaces/..., but it would
> lead to another type.
> Or use a keyword to the class, e.g. "autoclone class Color {...", and
> not the new name struct -> it would be clear that struct/classes use
> the same namespace.
> You maybe even could do "autoclone class DateTimeImmutable extends
> DateTime {}" to create the immutable version. (I see no reason why an
> "normal" class could not be extended into autoclone, but useless in
> most cases though)
>
> On the other hand, I would just use an array. (without any "magic"
> like methods on structs, yes you would have to write plain functions
> and not use OOP like methods).
>

Reply via email to