Chapter 10. Xyster_Type

Table of Contents

10.1. Overview
10.1.1. Creating
10.1.2. Basic Usage
10.2. Static Methods
10.2.1. Testing Value Equality
10.2.2. Hash Codes
10.2.3. Parameter Types

10.1. Overview

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.

10.1.1. Creating

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).

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.

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

10.1.2. Basic Usage

A Xyster_Type object offers many useful methods to assist you in working with different classes and types. getClass

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. isAssignableFrom

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. isInstance

This method determines if the value passed to the method is an instance of the type the object represents.

$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";
} isObject

This method returns true if the type the object represents is a class or an interface. It returns false if the type is a primitive type like string or array.

Any type where this method returns false will return null for the getClass method.