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 here if you are not familiar with them already: Magic methods in PHP.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.