Got another job that deals with PHP. I haven't used the language in years and admittedly not made much use of its object orientated facilities during the time I worked with it in the past. As expected even the later additions to PHP have their oddities and pitfalls. For example today I tried to implement the following
001 abstract class BaseClass {
002
003 private $propertyA;
004 private $propertyB;
005
006 abstract public function __construct($a, $b);
007 abstract public function output();
008
009 public function plusOne() {
010 $a = $this->propertyA+1;
011 $b = $this->propertyB+1;
012 $c = $this->propertyC+1;
013 print $a."\n";
014 print $b."\n";
015 print $c."\n";
016 }
017 }
018
019 class MyClass extends BaseClass {
020 use BaseClassTraits;
021
022 private $propertyC;
023
024 public function __construct($a, $b, $c = 0) {
025 $this->propertyA = $a;
026 $this->propertyB = $b;
027 $this->propertyC = $c;
028 }
029
030 public function output() {
031 print $this->propertyA."\n";
032 print $this->propertyB."\n";
033 print $this->propertyC."\n";
034 }
035 }
036
037 $c = new MyClass(5, 8, 3);
038 $c->output();
039 $c->plusOne();
My experience with object orientated languages had me expect the program to simply ouput 5, 8, 3, 6, 9, 4. But it turned out to be 5, 8, 3, 1, 1, 4. After a lot of confusion I had come to the premature conclusion that this was the time to use Traits.
001 trait BaseClassTraits {
002
003 public function plusOne() {
004 $a = $this->propertyA+1;
005 $b = $this->propertyB+1;
006 $c = $this->propertyC+1;
007 print $a."\n";
008 print $b."\n";
009 print $c."\n";
010 }
011 }
012
013 class MyClass extends BaseClass {
014 use BaseClassTraits;
015 //...
This simple addition (and the removal of plusOne() from the super class) got me the expected result. But after further wringing out my brains I realized all I ever needed to get it working was to change the property of the child class to protected too.
Honestly I'm at a loss of words. I had used the protected keywords on members of super classes before, but somehow missed that it might be necessary the other way around as well. I meant to rant about PHP being a subpar language, but it turns out I was merely being careless and apparently don't have much of a right to complain here. Still the way inheritance works in PHP doesn't sit quite right with me.