MIKESTOWE.COM

you are here

Weekly PHP Test

True or False: In PHP 5.4 Traits can have properties?


..

..

..

..

..

..

..

..

..

..

ANSWER:

True!

In PHP 5.4 Traits may contain properties as long as properties do not exist in the calling class. But beware, if the property already exists PHP will throw an error (fatal if the property isn’t identical to the trait property, and E_STRICT if it is).

PHP
1
2
3
4
5
6
7
8
9
10
trait demo {
public $demo = 'this is a demo';
public $test = 'this is a test';
public function cool() {
/* this is the method */
}
/* ... */
}

Valid

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
trait testTrait {
public $demo = 'test';
}
class testClass {
use testTrait;
function test() {
echo $this->demo;
}
/* ... */
}

E_STRICT Error

PHP
1
2
3
4
5
6
7
8
9
10
11
trait testTrait {
public $demo = 'test';
}
class testClass {
use testTrait;
public $demo = 'test';
/* ... */
}

Fatal Error:

PHP
1
2
3
4
5
6
7
8
9
10
11
trait testTrait {
public $demo = 10;
}
class testClass {
use testTrait;
public $demo = 'test';
/* ... */
}

Fatal Error:

PHP
1
2
3
4
5
6
7
8
9
10
11
trait testTrait {
public $demo = 'test';
}
class testClass {
use testTrait;
protected $demo = 'test';
/* ... */
}

.

PHP Manual:
http://php.net/manual/en/language.oop5.traits.php

Share this Page:
Facebook Twitter Linkedin Reddit Tumblr Email

Leave a Reply

Your email address will not be published. Required fields are marked *