# php 如何覆蓋trait函數並從覆蓋函數中調用它？

2 Answers

``````trait A {
function calc(\$v) {
return \$v+1;
}
}

class MyClass {
function calc(\$v) {
return \$v+2;
}
}

class MyChildClass extends MyClass{
}

class MyTraitChildClass extends MyClass{
use A;
}

print (new MyChildClass())->calc(2); // will print 4

print (new MyTraitChildClass())->calc(2); // will print 3
``````

``````trait A {
function calc(\$v) {
return parent::calc(\$v*3);
}
}
// .... other code from above
print (new MyTraitChildClass())->calc(2); // will print 8 (2*3 + 2)
``````

``````trait A {
function trait_calc(\$v) {
return \$v*3;
}
}

class MyClass {
function calc(\$v) {
return \$v+2;
}
}

class MyTraitChildClass extends MyClass{
use A {
A::trait_calc as calc;
}
}

class MySecondTraitChildClass extends MyClass{
use A {
A::trait_calc as calc;
}

public function calc(\$v) {
return \$this->trait_calc(\$v)+.5;
}
}

print (new MyTraitChildClass())->calc(2); // will print 6
echo "\n";
print (new MySecondTraitChildClass())->calc(2); // will print 6.5
``````
php traits

``````trait A {
function calc(\$v) {
return \$v+1;
}
}

class MyClass {
use A;

function calc(\$v) {
\$v++;
return A::calc(\$v);
}
}

print (new MyClass())->calc(2); // should print 4
``````

``````trait A {
function calc(\$v) {
return \$v+1;
}
}

class MyClass {
use A {
calc as traitcalc;
}

function calc(\$v) {
\$v++;
return traitcalc(\$v);
}
}
``````

``````trait ATrait {
function calc(\$v) {
return \$v+1;
}
}

class A {
use ATrait;
}

trait BTrait {
function calc(\$v) {
\$v++;
return parent::calc(\$v);
}
}

class B extends A {
use BTrait;
}

print (new B())->calc(2); // should print 4
``````

php   traits