User Tools

Site Tools


programmieren:cakephp:traits

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
programmieren:cakephp:traits [2026/09/17 16:10] – created adminprogrammieren:cakephp:traits [2026/09/18 16:32] (current) – multiple admin
Line 1: Line 1:
 ====== Traits ====== ====== Traits ======
  
-I should totally actually write stuff here+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 
 + 
 +<code php> 
 +use SomeRandomTrait; 
 +</code> 
 + 
 +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 
 + 
 +<code php> 
 +$this->explodeMalta(); 
 +</code> 
 + 
 +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: 
 + 
 +<code php> 
 +/** 
 + * 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); 
 +} 
 +</code> 
 + 
 +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.1789654249.txt.gz · Last modified: by admin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki