Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

PHP Interface Implementation Test

View implements_test.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
<?php
interface TestInterface
{
public function foo();
public function bar();
}
class TestClassA implements TestInterface
{
public function foo() { }
public function bar() { }
}
class TestClassB
{
public function foo() { }
public function bar() { }
}
$testClassA = new TestClassA();
$testClassB = new TestClassB();
/* is_a() Function
* ---------------
* http://uk3.php.net/manual/en/function.is-a.php
*/
echo "is_a() on TestClassA:\t\t";
var_dump(is_a($testClassA, 'TestInterface'));
echo "is_a() on TestClassB:\t\t";
var_dump(is_a($testClassB, 'TestInterface'));
/* instanceof Operator
* -------------------
* http://uk3.php.net/manual/en/language.operators.type.php
*/
echo "instanceof on TestClassA:\t";
var_dump($testClassA instanceof TestInterface);
echo "instanceof on TestClassB:\t";
var_dump($testClassB instanceof TestInterface);
/* Reflection
* ----------
* http://uk3.php.net/manual/en/book.reflection.php
*/
$reflection = new ReflectionClass('TestClassA');
echo "Reflection on TestClassA:\t";
var_dump($reflection->implementsInterface('TestInterface'));
$reflection = new ReflectionClass('TestClassB');
echo "Reflection on TestClassB:\t";
var_dump($reflection->implementsInterface('TestInterface'));
View implements_test.php
1 2 3 4 5 6 7
Shows the various ways that PHP code has of establishing whether a class implements an interface.
 
The TestInterface, TestClassA and TestClassB all have the same method signature but only TestClassA uses "implements" in its definition.
 
The script demonstrates that in every case, the "implements" part of the declaration is what is used to provide the return values for these assessments.
 
We can infer that when a class is used for the first time, the PHP runtime analyses the methods of the class and those of any interfaces it is supposed to implement and stores the result.
View implements_test.php
1 2 3 4 5 6 7 8
Output of the above:
 
is_a() on TestClassA: bool(true)
is_a() on TestClassB: bool(false)
instanceof on TestClassA: bool(true)
instanceof on TestClassB: bool(false)
Reflection on TestClassA: bool(true)
Reflection on TestClassB: bool(false)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.