Table of Contents
The type class is a helper for determining types of variables as well as calculating equality and hash codes. It has several useful methods to augment PHP's Reflection capabilities.
Xyster_Type
accepts either a string
name for the class it represents or a ReflectionClass
object. Xyster_Type
accepts names for
classes, interfaces, or names for PHP primitive types (array,
string, integer, boolean, and double).
<?php require_once 'Xyster/Type.php'; $typeByString = new Xyster_Type('ArrayObject'); $reflectionClass = new ReflectionClass('ArrayObject'); $typeByReflectionClass = new Xyster_Type($reflectionClass);
You can also create the object by using the static of
method and passing an instance of the object for which you need
the type. This works with both objects and primitive types.
<?php require_once 'Xyster/Type.php'; $myObject = new SplObjectStorage; $typeOfObject = Xyster_Type::of($myObject); echo $typeOfObject->getName() . "\n"; // prints SplObjectStorage $myValue = "a test"; $typeOfScalar = Xyster_Type::of($myValue); echo $typeOfScalar->getName() . "\n"; // prints string $myArray = array(1, 2, 3); $typeOfArray = Xyster_Type::of($myArray); echo $typeOfArray->getName() . "\n"; // prints array
A Xyster_Type
object offers many useful
methods to assist you in working with different classes and types.
If the type is an actual class or interface, the getClass
will return a ReflectionClass
object
for the type. Scalar values like array and string cannot be
used with ReflectionClass
like with
other object-oriented programming languages.
This method is borrowed from Java and does exactly the same thing. It determines if the type passed to the method is a child of or is the same as the type the object represents.
The $type
argument can be either a
string, a ReflectionClass
object or a
Xyster_Type
object.
This method determines if the value passed to the method is an instance of the type the object represents.
<?php $stringType = new Xyster_Type('string'); if ( $stringType->isInstance("This is a string") ) { echo "The argument is a string\n"; } interface Foo { function print(); } class Bar implements Foo { public function print() { } } $fooType = new Xyster_Type('Foo'); if ( $fooType->isInstance(new Bar()) ) { echo "The argument is a Foo\n"; }