Which php function can be used to determine if an object is an instance of a class?
Alphabet SoupSo now you know how to create your own functions in PHP, and you’ve spent the last few days busily inspecting your applications and turning repeated code fragments into functions. But functions are just the tip of the software abstraction iceberg. Lurking underneath is a three-letter acronym that strikes fear into the hearts of most newbie programmers. Show
OOP. If you’ve been programming for a while, you’ve probably heard the term OOP before – it stands for Object Oriented Programming, and refers to a technique whereby you create program “objects” and then use these objects to build the functionality you need into your program. PHP 5 is very big on OOP – it comes with a brand-spanking-new object model which finally brings PHP objects into conformance with standard OOP principles and offers OO programmers a whole bunch of new goodies to play with. Wondering how you can get in on this? Well, wonder no more. Your prayers have been answered. Over the course of this tutorial, I’m going to take a brief look at PHP’s OO capabilities (both PHP 4 and PHP 5), together with examples and explanations to demonstrate just how powerful it really is. I’ll be covering most of the basics – classes, objects, attributes and methods – and a couple of more advanced concepts - constructors, destructors, private methods and properties, and inheritance. And if you’re new to object-oriented programming, or just apprehensive about what lies ahead, don’t worry – I promise this will be a lot less painful than you think. And unlike dentists, I don’t lie. Back to classBefore beginning, though, let’s make sure that you have a clear idea of the concepts involved here. In PHP, a class is simply a set of program statements which perform a specific task. A typical class definition contains both variables and functions, and serves as the template from which to spawn specific instances of that class. These specific instances of a class are referred to as objects. Every object has certain characteristics, or properties, and certain pre-defined functions, or methods. These properties and methods of the object correspond directly with the variables and functions within the class definition. Once a class has been defined, PHP allows you to spawn as many instances of the class as you like. Each of these instances is a completely independent object, with its own properties and methods, and can therefore be manipulated independently of other objects. This comes in handy in situations where you need to spawn more than one instance of an object – for example, two simultaneous database links for two simultaneous queries, or two shopping carts. Classes also help you keep your code modular – you can define a class in a separate file, and include that file only in the scripts where you plan to use the class – and simplify code changes, since you only need to edit a single file to add new functionality to all your spawned objects. Animal AnticsTo understand this better, pick an animal, any animal. I pick the bear, because I like bears. Now ask yourself, can you consider this bear, within the framework of OOP, as an “object”? Why not? After all, every bear has certain characteristics – age, weight, sex – which are equivalent to object properties. And every bear can perform certain activities – eat, sleep, walk, run, mate – all of which are equivalent to object methods. Let’s take it a little further. Since all bears share certain characteristics, it is possible to conceive of a template Bear(), which defines the basic characteristics and abilities of every bear on the planet. Once this Bear() (“class”) is used to create a new $bear (“object”), the individual characteristics of the newly-created Bear can be manipulated independently of other Bears that may be created from the template. Now, if you sat down to code this class in PHP 5, it would probably look something like this:
Given this class, it’s now simple to spawn as many Bears as you like, and adjust the individual properties of each. Take a look:
As the illustration above shows, once new objects are defined, their individual methods and variables can be accessed and modified independent of each other. This comes in very handy, as the rest of this tutorial will show. Going deeperNow that you’ve got the concepts straight, let’s take a look at the nitty-gritty of a class definition.
Every class definition begins with the keyword class, followed by a class name. You can give your class any name that strikes your fancy, so long as it doesn’t collide with a reserved PHP word. A pair of curly braces encloses all class variables and functions, which are written as you would normally code them. PHP 5 also introduces the concept of visibility to the object model. Visibility controls the extent to which object properties and methods can be manipulated by the caller, and plays an important role in defining how open or closed your class is. Three levels of visibility exist, ranging from most visible to least visible: public, private and protected. Within the class definition, you can mark the visibility of a property or method by preceding it with one of the keywords – public, private, or protected. By default, class methods and properties are public; this allows the calling script to reach inside your object instances and manipulate them directly. If you don’t like the thought of this intrusion, you can mark a particular property or method as private or protected, depending on how much control you want to cede over the object’s internals (more on this shortly). Since the PHP 4 object model does not include support for visibility, the class definition above would not work in PHP 4. Instead, you would need to use the following:
From the above, it should be clear that class properties and methods in PHP 4 are always public …and there ain’t nuttin’ you can do about that! In order to create a new instance of a class, you use the new keyword to assign the newly created object to a PHP variable.
In English, the above would mean “create a new object of class Bear() and assign it to the variable $daddy “. You can now access all the methods and properties of the class via this variable. For example, the code
would mean “assign the value Daddy Bear to the variable $name of this specific instance of the class Bear()“, while the statement
would mean “execute the function sleep() for this specific instance of the class Bear()“. Note the -> symbol used to connect objects to their properties or methods, and the fact that the $ symbol is omitted when accessing properties of a class instance. This and thatIn case you need to access functions or variables within the class definition itself, both PHP 4 and PHP 5 offer the $this keyword, which is used to refer to “this” class. To see how this works, let’s alter the eat() method to accept a number of food units and then add that to the bear’s weight.
In this case, the $this prefix indicates that the variable to be modified exists within the class – or, in English, “add the argument provided to eat() to the variable $weight within this object”. The $this prefix thus provides a convenient way to access variables and functions which are “local” to the class. Here’s an example of how it works:
The output of this will read: Baby Bear weighs 1000 units Brother Bear weighs 1000 units Baby Bear is eating 100 units of food... Baby Bear is eating 50 units of food... Brother Bear is eating 11 units of food... Baby Bear now weighs 1150 units Brother Bear now weighs 1011 units Under constructionIt’s also possible to automatically execute a function when the class is called to create a new object. This is referred to in geek lingo as a constructor and, in order to use it, your PHP 5 class definition must contain a special function, __construct(). For example, if you’d like all newly born bears to be brown and weigh 100 units, you could add this to your class definition:
In PHP 4, your constructor must have the same name as the class. Here’s the equivalent code for PHP 4:
Now, try creating and using an instance of the class:
Here, the constructor automatically sets default properties every time an object of the class is instantiated. Therefore, when you run the script above, you will see this: Baby Bear is brown and weighs 100 units at birth Hands offAs noted previously, PHP 5 makes it possible to mark class properties and methods as private, which means that they cannot be manipulated or viewed outside the class definition. This is useful to protect the inner workings of your class from manipulation by object instances. Consider the following example, which illustrates this by adding a new private variable, $_lastUnitsConsumed, to the Bear() class:
Now, since the $_lastUnitsConsumed variable is declared as private, any attempt to modify it from an object instance will fail. Here is an example:
In a similar way, class methods can also be marked as private - try it out for yourself and see. Extending yourselfTwo of the best things about OOP, whether in PHP 4 or in PHP 5, are extensibility and inheritance. Very simply, this means that you can create a new class based on an existing class, add new features (read: properties and methods) to it, and then create objects based on this new class. These objects will contain all the features of the original parent class, together with the new features of the child class. As an illustration, consider the following PolarBear() class, which extends the Bear() class with a new method.
The extends keyword is used to extend a parent class to a child class. All the functions and variables of the parent class immediately become available to the child class. This is clearly visible in the following code snippet:
In this case, the final call to $tom->swim() will fail and cause an error, because the Bear() class does not contain a swim() method. However, none of the calls to $bob->run() or $bob->kill() will fail, because as a child of the Bear() class, PolarBear() inherits all the methods and properties of its parent. Note how the parent class constructor has been called in the PolarBear() child class constructor - it's a good idea to do this so that all necessary initialization of the parent class is carried out when a child class is instantiated. Child-specific initialization can then be done in the child class constructor. Only if a child class does not have a constructor, is the parent class constructor automatically called. You can do this in PHP 4, too. Here's a PHP 4 version of the PolarBear class definition:
To prevent a class or its methods from being inherited, use the final keyword before the class or method name (this is new in PHP 5 and will not work in older versions of PHP). Here's an example, which renders the Bear() class un-inheritable (if that's actually a word):
Ending on a high noteJust as there are constructors, so also are there destructors. Destructors are object methods which are called when the last reference to an object in memory is destroyed, and they are usually tasked with clean-up work – for example, closing database connections or files, destroying a session and so on. Destructors are only available in PHP 5, and must be named __destruct(). Here’s an example:
Here, once the script ends, no reference will exist for $daddy, and so the destructor will be called automatically. The output would look like this: Daddy Bear is killing prey... Daddy Bear is eating 2000 units of food... Daddy Bear is running... Daddy Bear is eating 100 units of food... Daddy Bear is dead. He was 10 years old and 2200 units heavy. Rest in peace! Discovering new thingsPHP 4 and PHP 5 come with a bunch of functions designed to let you discover object properties and methods, and find out which class an object belongs to. The first two of these are the get_class() and get_parent_class() functions, which tell you the name of the classes which spawned a particular object. Consider the following class definition:
And now consider the following script, which uses get_class() and get_parent_class() to retrieve the class name from an instance:
You can view all the properties exposed by a class with get_class_vars(), and all its methods with get_class_methods() function. To view properties of the specific object instance, use get_object_vars() instead of get_class_vars(). Here is an example:
and here is some sample output: Class properties: Array ( [name] => [weight] => ) Class methods: Array ( [0] => kill [1] => __construct [2] => eat [3] => run [4] => sleep ) Instance properties: Array ( [name] => Joe Bear [weight] => 1000 ) As noted in one of the previous segments of this tutorial, the print_r() function allows you to look inside any PHP variable, including an object. It’s extremely useful, so note it down for future reference. Access deniedAnd now that you know the basics of how objects work in PHP, let’s wrap this up with a real-world example. Consider the following userAuth() class, which exposes methods to validate a user login using an encrypted password file such as /etc/passwd or .htaccess, both of which are used on Unix systems (i.e. most of the Internet). I’ll assume here that the passwords in the password file are encrypted with MD5, and use a 12-character salt beginning with $1$:
Most of this should be clear to you from the examples in previous pages. In case it isn’t, the following script should help you understand what’s happening:
Here, the username and password is passed to the object constructor, as is the name and path of the file containing authentication credentials. The authenticateUser() method takes care of parsing the password file and checking if the user exists and the password is correct. Depending on what it finds, a result code is generated and stored in the private variable $_resultCode. This variable can be read through the getResultCode() method, and an appropriate message displayed. And since this entire thing is neatly encapsulated in a class, I can take it anywhere, use it in any script – even inside another application – and extend it to support different types of authentication schemes and containers. There’s a lot more you can do with objects, especially in PHP 5; I’ve restrained myself here because I didn’t want to confuse you too much with talk of overloading, abstract classes and static methods. If you’re interested, however, drop by http://www.php.net/manual/en/language.oop.php for more. And make sure you come back for Part Eight of PHP 101, because I’m going to show you how to hook your scripts up to a MySQL database. How can we determine whether a PHP variable is an instantiated object of a certain class?instanceof is used to determine whether a PHP variable is an instantiated object of a certain class:. Example #1 Using instanceof with classes. ... . Example #2 Using instanceof with inherited classes. ... . Example #3 Using instanceof to check if object is not an instanceof a class. ... . Example #4 Using instanceof with interfaces.. What is instance of an example of PHP?An instance is an object that has been created from an existing class. Creating an object from an existing class is called instantiating the object. To create an object out of a class, the new keyword must be used. Classes should be defined prior to instantiation.
What is PHP instance variable?Instance Variable: These variables are declared within a class but outside a method, constructor, or block and always get a default value. These variables are usually created when we create an object and are destroyed when the object is destroyed.
Which of the following is a special method executed when a new object is created from a class?Constructor. The constructor method is a special method for creating and initializing an object created with a class . There can only be one special method with the name "constructor" in a class.
|