PHP ZCE mock test, interview preparation, daily lessons under chalk talk

Friday, January 20, 2012

PHP instanceOf and Type Hinting usage

instanceOf: It is one of the type operator present in php.


- It is used to determine whether a PHP variable is an instantiated object of a particular class.


- It can also be used to determine whether a variable is inheriting properly from another class. 


- Also used to determine whether a variable is an instantiated object of a class that implements an interface.




Example:


<?php
class ParentClass
{
}

class MyClass extends ParentClass
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>

Output:

bool(true)
bool(true)




Type Hinting: It is a feature that is added in PHP5


- It allows functions to force parameters to be objects by specifying the name of the class in the function prototype.


- It allows to use NULL as default parameter value.


Example:


    //First parameter must be an object of type OtherClass
     public function test(OtherClass $otherclass)

    //First parameter must be an array    public function test_array(array $input_array) 


Question 1:



When checking to see if two variables contain the same instance of an object, which of the following comparisons should be used?
 1)    if($obj1->equals($obj2) && ($obj1 instanceof $obj2))
 2)    if($obj1->equals($obj2))
 3)    if($obj1 === $obj2)
 4)    if($obj1 instanceof $obj2)
 5)    if($obj1 == $obj2)




Question 2:



In PHP 5 you can use the ______ operator to ensure that an object is of a particular type. You can also use _______ in the function declaration.
1)     instanceof, is_a
2)     instanceof, type-hinting
3)     type, instanceof
4)     ===, type-hinting
5)     ===, is_a


Solution 1:
3)     if($obj1 === $obj2)


Solution 2:
2)     instanceof, type-hinting

No comments:

Post a Comment