Skip to content

Instantly share code, notes, and snippets.

@mike-potter
Created September 16, 2016 13:43
Show Gist options
  • Save mike-potter/c380ebc4f05469cfec5a8cf464995e6d to your computer and use it in GitHub Desktop.
Save mike-potter/c380ebc4f05469cfec5a8cf464995e6d to your computer and use it in GitHub Desktop.
Testing Traits
<?php
class baseClass {
protected function protfunc() {
return "protBase";
}
public function pubfunc() {
return "pubBase";
}
public function chainProt() {
return $this->protfunc() . "\n";
}
public function chainPub() {
return $this->pubfunc() . "\n";
}
}
trait myTrait {
protected function protfunc() {
return "protTrait";
}
public function pubfunc() {
return "pubTrait";
}
}
class childClass extends baseClass {
use myTrait;
}
$base = new baseClass();
print "Base:\n";
print $base->chainProt();
print $base->chainPub();
$child = new childClass();
print "Child:\n";
print $child->chainProt();
print $child->chainPub();
@mike-potter
Copy link
Author

This prints:
Base: protBase pubBase Child: protTrait pubTrait

So the Trait can override both public and protected functions. When the parent chain function is called, it resolves the correct protected function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment