Page 1 of 1

PHP Traits (5.4)

Posted: Sat Mar 03, 2012 9:31 am
by bowersbros
Okay, this is pretty much based on how I think that they work. I could be partly, or entirely wrong. And my code isn't being tested for this, since I haven't upgraded to 5.4 on my localhost yet.

But I digress.

So, since PHP is a single inheritance language. There are occasions, when you need things across multiple classes, but you can't because your already extending a class, and inheriting their properties.
class somename extends something,else {

}
is invalid. since you can't extend multiple classes.

SO what do you do?

Well, with php 5.4, a new languages construct called Traits is here

It saves you from having to copy and paste that other class over, and so on.
trait else {
 function someName(){
return 'hello';
}
}

class helloWorld {
 use else;
echo someName();
}

$hello = new helloWorld;
helloWorld::someName();

That should print out 'hello'

Thats my basic understanding of it anyway.

you can extend another class still, and if you were to have a naming conflict between two traits, then you would use the new insteadof operator

As such
trait one {
 function traitName(){
return 'one';
}
}
trait two {
function traitName(){
return 'two';
}
}

class name {
 use one,two;
 one:: traitName instead of two;

}
That would use the traitName from one, and not two by default. But two is still accessible by using two::traitName() inside of the class.

Alternatively, if you need access to either at any time, without referencing their class, then you can do that by using the as and renaming one of them temporarily.
/* same as above */

class name {

use one,two;
one:: traitName as traitNameOne;
}
That would allow for traitNameOne and traitName to be used, where they reference trait one and two respectively.

Re: PHP Traits (5.4)

Posted: Sat Mar 03, 2012 11:14 pm
by jacek
Ohhhh a class can use multiple traits ? That makes them make a lot more sense !

I really doubt I will ever use this to be honest. I have gotten so used to designing everything with single inheritance in mind.

Re: PHP Traits (5.4)

Posted: Tue May 22, 2012 5:00 pm
by bowersbros
So yeah, 2 months down the line. Still haven't used it.

I am beginning to wonder why they bothered implementing this, when its fairly clear that it isn't all that useful, since people have worked around PHP being a single inheritance language for such a long time.

Re: PHP Traits (5.4)

Posted: Tue May 22, 2012 6:31 pm
by jacek
Yeah I can’t really see a sensible usage example that can;t easily be done in other ways. I guess it's a nice feature though.