Quantcast
Viewing all articles
Browse latest Browse all 23908

Re: [PHP-DEV] Initializer List

On Wed, 2015-06-17 at 10:03 +0200, Lorenzo Fontana wrote:
> - In C++ using initializer list is used over assignment also for
> performance reasons but right now I can't say if this can be achieved in
> PHP or not.
>
> Initializer lists in C++:
> http://en.cppreference.com/w/cpp/language/initializer_list

Mind that C++ doesn't do this to make code "nice" or "short" or whatever
in that area but primarily due to need of control. Not having
initializer lists means that object members in C++ have to be default
constructible. Given C++ code like this

struct C {
SomeType a;
C(const SomeType& a) {
this->a = a;
}
}

first calls the default constructor SomeType::SomeType() for a and then
the assignment constructor (SomeType::operator=(const SomeType&) or
similar)

Another reason why C++ needs this ist const-correctness. In the example
above it will fail if a is marked as const as the default constructor
will initialize and assignment on const objects isn't valid.

In PHP however the default constructor equivalent is setting the type to
NULL which is (almost) for free while allocating the variable. Thus the
need isn't there.

You also write

> public function __construct() : host("127.0.0.1") {};

as example. But that ignores PHP's way to define default values:

class Foo {
private $host = "127.0.0.1";
}

would be the PHP version to what you propose. At the same time I am
confussed, by using a literal string there I assume you want to allow
expressions there, but in other examples, like

> public function __construct($name, $surname, $age) : name(name),
> surname(surname), age(age) {};

you are not handling expressions (unless the constructor arguments are
being ignored and properties are being initialized using the global
constants name, surname and age, which I assume you didn't intend)

You are also not discussing inheritance. Can I do

class Base { /* .... */ }
class Extended extends Base {
public function __construct() : parent(42) {}
}

how does that relate to parent::__construct()?


In summary:
I consider this syntactic sugar which in my opinion doesn't increase
readability and in other languages solves an issue PHP doesn't have.

johannes

Viewing all articles
Browse latest Browse all 23908

Trending Articles