User Tools

Site Tools


programmieren:cakephp:traits

Traits

Traits in PHP are an easy way to reuse common code that is used in multiple different places.

You can load it in a class by simply calling

use SomeRandomTrait;

You can do it for multiple traits.

This basically makes the traits code part of the class, so if the trait has a function called explodeMalta() you can call it in the class like

$this->explodeMalta();

But traits cannot extend any classes nor implement any interfaces or use traits, it esentially mends with the scope of the class its used in which can lead to it either working fine or fully breaking with the exact same data only depending on what scope you call it in.

Also very interesting is that if you call a traits function, the trait has access to the class that called it.

For example this method:

/**
 * Asserts if the given value, which has its contents normalized to be comparable, equals given expected value
 *
 * @param array $expected The expected result as an array.
 * @param EntityInterface|iterable $actual The actual data in form of any iterable or EntityInterface.
 * @param string $message The optional failure message that will be appended to the generated message.
 * @return void
 */
public function assertEqualsNormalizedArray(
    array $expected,
    EntityInterface | iterable $actual,
    string $message = ''
): void {
    $normalizedActual = $this->normalizeArray($actual);
 
    self::assertEquals($expected, $normalizedActual, $message);
}

It accesses self::assertEquals() but its a trait it cannot extend TestCase, so this only works if the class calling that function extends TestCase.

programmieren/cakephp/traits.txt · Last modified: by admin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki