Skip to content

Instantly share code, notes, and snippets.

@emeraldinspirations
Created July 31, 2017 07:39
Show Gist options
  • Select an option

  • Save emeraldinspirations/34bf8bc2faf298511cc124e66d8201bb to your computer and use it in GitHub Desktop.

Select an option

Save emeraldinspirations/34bf8bc2faf298511cc124e66d8201bb to your computer and use it in GitHub Desktop.
2017-07-31 - Why casting to Interface in PHP would be useless
<?php
/**
* Why casting to Interface in PHP would be useless.
*
* In applications I write, all function parameters are type hinted to
* interfaces except for base types and value objects. This allows the unit
* tests to supply dummy objects.
*
* The interfaces themselves have no logic inside, so the only test that they
* need to pass, is that they have the required functions. Unfortunately,
* inside PHP, there really is no simple way to do this.
*
* Therefore, I decided to test the interface using the first class that
* implements it. Therefore, when I did the 'get to red' step of TDD and
* 'Write only enough code to get the test to fail' I could write
* `$Object->NewMethod();` and the test would fail. In order to 'get to green'
* I would be forced to add the function BOTH to the interface and to it's
* implementing class.
*
* Unfortunately, as you can see below, that doesn't work in PHP. Basically,
* it is called type 'hinting' for a reason.
*
* @author Matthew "Juniper" Barlett <emeraldinspirations@gmail.com>
* @copyright 2017 Matthew "Juniper" Barlett <emeraldinspirations@gmail.com>
* @license MIT
*/
interface DemoInterface
{
function FunctionInBothClassAndInterface();
}
class DemoClass implements DemoInterface
{
public function FunctionInBothClassAndInterface() {
return 'I work as I should!';
}
public function FunctionNotInInterface() {
return 'Developer forgot to add to interface, not exposed in unit test';
}
}
function UnitTest()
{
$Variable = (DemoInterface) new DemoClass();
// PHP Parse error: syntax error, unexpected 'new' (T_NEW) in ...
$Variable = (DemoInterface) (new DemoClass());
// PHP Notice: Use of undefined constant DemoInterface - assumed ...
$TypeCastToInterface = function (DemoInterface $Object) : DemoInterface {
return $Object;
};
$Variable = $TypeCastToInterface(new DemoClass());
var_dump($Variable);
/*
object(DemoClass)#2 (0) {
}
*/
$Variable->FunctionNotInInterface();
// Unit test SHOULD fail, but PHP does not detect issue
}
UnitTest();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment