InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

Menu
  • Home
  • Sitemap

Python Programming Language Best Tutorials and Code Examples

Learn Python Right Now!
Home
PHP
Checking If an Object Is an Instance of a Specific Class in PHP
PHP

Checking If an Object Is an Instance of a Specific Class in PHP

InfinityCoder November 25, 2016

You want to check if an object is an instance of a specific class.

To check that a value passed as a function argument is an instance of a specific class, specify the class name in your function prototype:

1
2
3
4
public function add(Person $person) {
         // add $person to address book
    }
}

In other contexts, use the instanceof operator:

1
2
3
4
5
6
$media = get_something_from_catalog();
if ($media instanceof Book) {
// do bookish things
} else if ($media instanceof DVD) {
// watch the movie
}

One way of enforcing controls on your objects is by using type hints. A type hint is a way to tell PHP that an object passed to a function or method must be of a certain class.
To do this, specify a class name in your function and method prototypes. You can also require that an argument is an array, by using the keyword array.

This only works for classes and arrays, though, not for any other variable types. You cannot, for example, specify strings or integers.

For example, to require the first argument to your AddressBook class’s add() method to be of type Person:

1
2
3
4
5
6
class AddressBook {
 
   public function add(Person $person) {
       // add $person to address book
   }
}

Then, if you call add() but pass a string, you get a fatal error:

1
2
3
4
5
6
7
$book = new AddressBook;
 
$person = 'Rasmus Lerdorf';
 
$book->add($person);
 
PHP Fatal error: Argument 1 must be an object of class Person in...

Placing a type hint of Person in the first argument of your function declaration is equivalent to adding the following PHP code to the function:

1
2
3
4
5
public function add($person) {
       if (!($person instanceof Person)) {
              die("Argument 1 must be an instance of Person");
        }
}

The instanceof operator checks whether an object is an instance of a particular class. This code makes sure $person is a Person.
The instanceof operator also returns true with classes that are subclasses of the one you’re comparing against. For instance:

1
2
3
4
5
6
7
8
9
10
11
class Person { /* ... */ }
 
class Kid extends Person { /* ... */ }
 
$kid = new Kid;
 
if ($kid instanceof Person) {
       print "Kids are people, to.\n";
}
 
Kids are people, too.

Last, you can use instanceof to see if a class has implemented a specific interface:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
interface Nameable {
    public function getName();
    public function setName($name);
}
 
class Book implements Nameable {
        private $name;
 
    public function getName() {
        return $this->name;
    }
 
     public function setName($name) {
        return $this->name = $name;
     }
}
 
$book = new Book;
if ($book instanceof Book) {
    print "You can name a Book.\n";
}
 
You can name a Book

Type hinting has the side benefit of integrating API documentation directly into the class itself. If you see that a class constructor takes an Event type, you know exactly what to provide the method.

Additionally, you know that the code and the “documentation” must always be in sync, because it’s baked directly into the class definition.
You can also use type hinting in interface definitions, which lets you further specify all your interface details.
However, type hinting does come at the cost of less flexibility.

There’s no way to allow a parameter to accept more than one type of object, so this places some restrictions on
how you design your object hierarchy.
Also, the penalty for violating a type hint is quite drastic—the script aborts with a fatal error. In a web context, you may want to have more control over how errors are handled and recover more gracefully from this kind of mistake.

Implementing your own form of type checking inside of methods lets you print out an error page if you choose.
Last, unlike some languages, you cannot use type hinting for return values, so there’s no way to mandate that a particular function always returns an object of a particular type.

Share
Tweet
Email
Prev Article
Next Article

Related Articles

Requiring Multiple Classes to Behave Similarly in PHP
You want multiple classes to use the same methods, but …

Requiring Multiple Classes to Behave Similarly in PHP

Guarding Against Multiple Submissions of the Same Form in PHP
You want to prevent a user from submitting the same …

Guarding Against Multiple Submissions of the Same Form in PHP

About The Author

InfinityCoder
InfinityCoder

Leave a Reply

Cancel reply

Recent Tutorials InfinityQuest

  • Adding New Features to bash Using Loadable Built-ins in bash
    Adding New Features to bash Using Loadable …
    June 27, 2017 0
  • Getting to the Bottom of Things in bash
    Getting to the Bottom of Things in …
    June 27, 2017 0

Recent Comments

  • fer on Turning a Dictionary into XML in Python
  • mahesh on Turning a Dictionary into XML in Python

Categories

  • Bash
  • PHP
  • Python
  • Uncategorized

InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more

About Us

Start learning your desired programming language with InfinityQuest.com.

On our website you can access any tutorial that you want with video and code examples.

We are very happy and honored that InfinityQuest.com has been listed as a recommended learning website for students.

Popular Tags

binary data python CIDR convert string into datetime python create xml from dict python dictionary into xml python how to create xml with dict in Python how to write binary data in Python IP Address read binary data python tutorial string as date object python string to datetime python

Archives

  • June 2017
  • April 2017
  • February 2017
  • January 2017
  • December 2016
  • November 2016
Copyright © 2021 InfinityQuest - Programming Code Tutorials and Examples with Python, C++, Java, PHP, C#, JavaScript, Swift and more
Programming Tutorials | Sitemap