Search code examples
phpstrategy-pattern

Simple strategy pattern returns unwanted echo output


when I run the script

<?php

interface IBrakeBehaviour {
    public function brake();
}

class Brake implements IBrakeBehaviour {
    public function brake() {
        echo "Simple Brake applied.";
    }
}

class BrakeWithABS implements IBrakeBehaviour {
    public function brake() {
        echo "Brake with ABS applied.";
    }
}

class Car {
    private $_brakeBehavior;

    public function __construct(IBrakeBehaviour $brakeBehavior)
    {
        $this->_brakeBehavior = $brakeBehavior;
    }

    public function brake() {
        $this->_brakeBehavior->brake();
    }
}

$bmw = new Car(new Brake());
$audi = new Car(new BrakeWithABS());

it automatically echos "Simple Brake applied." But that message should appear when I execute

$bmw->brake(); or $audi->brake();

and not before.

Does anybody know what I am doing wrong? Many thanks in advance.

Herbert


Solution

  • In PHP you can both use the __construct and, if you wish, name the constructor the same as the class (not 100% sure if this applies to all versions).
    So the problem you are experiencing is that your Brake class implements a constructor instead of the method you think it implements (brake).

    Now, one could think that there would be a difference between Brake() and brake(), but no. In php, method/function names are case insensitive, so they are the same...

    How to bypass this issue?
    If you implement the constructor as __construct before implementing the brake function, it should work, ie:

    class Brake {
      public function __construct() {} // First
      public function Brake() {}       // Then this
    }
    

    Else you might get a Redefining already defined constructor error.