PHP toString Equivalent

PHP toString Equivalent

Written by Dev Dojo on Jun 22nd, 2016 Views Report Post

Converting a PHP variable to a string is pretty easy. We can simply cast the variable to a string and echo the contents like so:

<?php
	$variable1 = 100;
	echo (string) $variable1;
?>

This is one of the most common ways to convert a value into a string which is referred to as casting a variable. In the code above we have 'casted' the variable to a string.

Another similar option would be to use the strval() function, which accomplishes the same thing. The conversion is automatically done within the scope of the expression where the string is needed. This usually happens when print or echo functions are used or with a variable.

Unfortunately this is only applicable if that variable is one of the following types:

  • Boolean – A Boolean value TRUE is converted to string “1” whereas Boolean FALSE is converted to an empty string “”
  • Integer – When an integer is converted into a string, the same number is textually represented in String form
  • Array – Arrays too can be converted strings. But echo and print cannot be directly used to display contents of the array. Instead, they have to be used as echo $arr[‘foo’]
  • Objects – Up until PHP 4, Objects could be converted to string form “Object”. For viewing their class get_class() function was used.

All other types will not be able to be converted into a string and unfortunately PHP does not have a direct method like ToString() in .NET, Java, or Javascript.

But luckily for us everything changed with PHP 5, when a new magic function __toString() was introduced.

Magic Function __toString()

Being a loosely typed language, the same variable in PHP can be referred or used as a number, object or string. Now, the method __toString() can be called when an object needs to be treated like a string.

This magic function does not accept any arguments with it and returns a string value. All the magic functions in PHP are reserved and they cannot be used for any other purpose. Also, all the functions that start with a double underscore ( __ ) are especially reserved for Objects.

Exceptions and errors with __toString()

__toString() must always return a string, otherwise the function gives a fatal error. Also, there is no way to throw an exception from within  __toString() resulting into an error.

That is why the best way out would be to use a try-catch code inside the __toString() function. So that, even if an exception is thrown, it can be caught.

Using the __toString() magic function we can now create a new class object and when we echo out an instance of that object the magic function will automatically be called like so:

<?php

// Create Your Class
class MyClass
{
    public $name;

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

    public function __toString()
    {
        try 
        {
            return (string) $this->name;
        } 
        catch (Exception $exception) 
        {
            return '';
        }
    }
}

$classObject = new MyClass('John Doe');
echo $classObject;

?>

In conclusion

It is easy to say that __toString() is an incredibly useful function in PHP. Though the errors can be a bit of an issue with it, when executed with the right code, there shouldn't be any problems at all.

Comments (0)