Dev / PHP

Checking out an Object in PHP: 3 Quick Functions!

phpDid you ever have to check if an object is an instance of this, or if it has this property, or if it has this method? It’s a common thing when working with other people’s code. Here’s how:

  • is_a() – Is this an instance of this class?
  • property_exists() – does this object have this property?
  • method_exists() – does this object have this method?

All of these return either true or false.

Here’s how to use them:

<?php

 class Person {

  function __construct($name) {
   $this->name = $name;
  }

  public function walk() {
   return "walking..";
  }
 }

 $person = new Person("Bill");

 if (is_a($me, "Person")) {
  echo "I'm a person, ";
 }
 if (property_exists($me, "name")) {
  echo "I have a name, ";
 }
 if (method_exists($me, "walk")) {
  echo "and I know how to walk!";
 }

?>

Pretty easy. 🙂

Advertisements

2 thoughts on “Checking out an Object in PHP: 3 Quick Functions!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s