Showing posts with label PHP Magic Methods. Show all posts
Showing posts with label PHP Magic Methods. Show all posts

Thursday, 18 September 2014

Difference between isset() and __isset() in PHP

isset()

It is a language construct that checks the initialization of variables or class properties:
$a = 10;

isset($a);     // true
isset($a, $b); // false

class Test
{
    public $prop = 10;
}

$obj = new Test;
isset($obj->prop); // true

__isset()

It is a magic method that is invoked when isset() or empty() check non-existent or inaccessible class property:
class Test
{
    public function __isset($name) {
        echo "Non-existent property '$name'";
    }
}

$obj = new Test;
isset($obj->prop); // prints "Non-existent property 'prop'" and return false

Difference:

           isset()                               __isset()
Language construct                    | Magic method
                                      |
Always return bool                    | Result depends on custom logic*
                                      |
Must be invoked in code               | Called automatically by event
                                      |
Unlimited number of parameters        | Has only one parameter
                                      |
Can be used in any scope              | Must be defined as method**
                                      |
Is a reserved keyword                 | Not a reserved keyword
                                      |
Can't be redefined (Parse error)      | Can be redefined in extended class***
__isset() result anyway will be automatically casted as bool.
Actually you can define custom function __isset() but it has nothing to do with the magic method.

Thursday, 4 September 2014

How would you convert a PHP variable to a string? Is there something like the toString method that Java has in PHP?

PHP has casting operators that can be used to convert non-string variables into strings. Here is how to use a casting operator to convert a variable to a string in PHP:

Example of PHP’s equivalent to toString

// this is an integer:
$nonStringVar = 123;

/*now $stringVar is a string because
   the "(string)" performs a type cast
   and returns the string equivalent
   of the integer
*/
$stringVar = (string)$nonStringVar;
The casting operator is fairly close in functionality to the toString method in Java, but read below because PHP also has a it’s own __toString method.

Using the strval function to convert a variable to a string

You can also use the function strval to get the string value of a variable.
// this is an integer:
$nonStringVar = 123;

//now $stringVar is a string
$aString = strval($nonStringVar);

PHP does have a __toString magic method


PHP also provides a method called __toString that is defined by the programmer, and that basically tells a class how to act when it is treated like a string. When would a class be treated like a string? Well, suppose you have a class called SomeClass, and an object of that class called $someObject. If you decide to do something like this: “echo $someObject;”, then what exactly should be output in that scenario? Well, that is up to you to decide – because whatever you define in __toString method is what will be output to the page. You can decide to output all of the class’s instance variables, output a particular string, etc. – but whatever you do the __toString method will have to return a string.
Here is an example of the __toString method in action:
class SomeClass
{
    public $aVariable;

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

    public function __toString()
    {
        return $this->aVariable;
    }
}

$someObject = new SomeClass('Testing 123');


/* this will indirectly call the toString method:
    which will output the string 'Testing 123'
*/
echo $someObject;


The __toString method is a magic method – you can read more about magic methods

Magic methods in PHP

PHP functions that start with a double underscore – a “__” – are called magic functions (and/or methods) in PHP. 

Magic methods are functions that are always defined inside classes, and are not stand-alone (outside of classes) functions. 

The magic functions available in PHP are: 
__construct(),
 __destruct(),
 __call(),
 __callStatic(),
 __get(),
 __set(),
 __isset(),
 __unset(),
 __sleep(), 
 __wakeup(),
 __toString(),
 __invoke(),
 __set_state(),
 __clone(), and 
 __autoload()

Why are they called magic functions?

PHP does not provide the definitions of the magic functions – the programmer must actually write the code that defines what the magic function will do. 

But, magic functions will never directly be called by the programmer – actually, PHP will call the function ‘behind the scenes’. 

This is why they are called ‘magic’ functions – because they are never directly called, and they allow the programmer to do some pretty powerful things. 

Confused? An example will help make this clear.

Example of using the __construct() magic function in PHP

The most commonly used magic function is __construct(). 
This is because as of PHP version 5, the __construct method is basically the constructor for your class. 

If PHP 5 can not find the __construct() function for a given class, then it will search for a function with the same name as the class name – this is the old way of writing constructors in PHP, where you would just define a function with the same name as the class.

Now, here is an example of a class with the __construct() magic function:
class Animal {
        public $height;      // height of animal  
        public $weight;     // weight of animal

         public function __construct($height, $weight) 
        {
                 $this->height = $height;  //set the height instance variable
                 $this->weight = $weight; //set the weight instance variable
        }
}

In the code above, we have a simple __construct function defined that just sets the height and weight of an animal object. 

So let’s say that we create an object of the Animal class with this code:
Animal obj = new Animal(5, 150);
What happens when we run the code above? 

Well, a call to the __construct() function is made because that is the constructor in PHP 5. 

And the obj object will be an object of the Animal class with a height of 5 and a weight of 150. So, the __construct function is called behind the scenes. Magical, isn’t it?