PHP equivalent of .NET/Java's toString()


How do I convert the value of a PHP variable to string?

I was looking for something better than concatenating with an empty string:

$myText = $myVar . '';

Like the ToString() method in Java or .NET.

This question is tagged with php string

~ Asked on 2008-08-26 13:56:49

25 Answers


You can use the casting operators:

$myText = (string)$myVar;

There are more details for string casting and conversion in the Strings section of the PHP manual, including special handling for booleans and nulls.

~ Answered on 2008-08-26 14:01:50


This is done with typecasting:

$strvar = (string) $var; // Casts to string
echo $var; // Will cast to string implicitly
var_dump($var); // Will show the true type of the variable

In a class you can define what is output by using the magical method __toString. An example is below:

class Bottles {
    public function __toString()
        return 'Ninety nine green bottles';

$ex = new Bottles;
var_dump($ex, (string) $ex);
// Returns: instance of Bottles and "Ninety nine green bottles"

Some more type casting examples:

$i = 1;

// int 1
var_dump((int) $i);

// bool true
var_dump((bool) $i);

// string "1"
var_dump((string) 1);

~ Answered on 2008-08-26 14:11:01


Use print_r:

$myText = print_r($myVar,true);

You can also use it like:

$myText = print_r($myVar,true)."foo bar";

This will set $myText to a string, like:

array (
  0 => '11',
)foo bar

Use var_export to get a little bit more info (with types of variable,...):

$myText = var_export($myVar,true);

~ Answered on 2010-08-24 17:31:52


You can either use typecasting:

$var = (string)$varname;

or StringValue:

$var = strval($varname);

or SetType:

$success = settype($varname, 'string');
// $varname itself becomes a string

They all work for the same thing in terms of Type-Juggling.

~ Answered on 2010-01-02 08:51:14


How do I convert the value of a PHP variable to string?

A value can be converted to a string using the (string) cast or the strval() function. (Edit: As Thomas also stated).

It also should be automatically casted for you when you use it as a string.

~ Answered on 2008-08-26 14:00:48


You are looking for strval:

string strval ( mixed $var )

Get the string value of a variable. See the documentation on string for more information on converting to string.

This function performs no formatting on the returned value. If you are looking for a way to format a numeric value as a string, please see sprintf() or number_format().

~ Answered on 2009-12-20 15:24:10


For primitives just use (string)$var or print this variable straight away. PHP is dynamically typed language and variable will be casted to string on the fly.

If you want to convert objects to strings you will need to define __toString() method that returns string. This method is forbidden to throw exceptions.

~ Answered on 2008-08-26 14:15:46


Putting it in double quotes should work:

$myText = "$myVar";

~ Answered on 2008-08-26 13:58:02


I think it is worth mentioning that you can catch any output (like print_r, var_dump) in a variable by using output buffering:

    $result = ob_get_clean();

Thanks to: How can I capture the result of var_dump to a string?

~ Answered on 2014-02-25 23:28:41


In addition to the answer given by Thomas G. Mayfield:

If you follow the link to the string casting manual, there is a special case which is quite important to understand:

(string) cast is preferable especially if your variable $a is an object, because PHP will follow the casting protocol according to its object model by calling __toString() magic method (if such is defined in the class of which $a is instantiated from).

PHP does something similar to

function castToString($instance) 
    if (is_object($instance) && method_exists($instance, '__toString')) {
        return call_user_func_array(array($instance, '__toString'));

The (string) casting operation is a recommended technique for PHP5+ programming making code more Object-Oriented. IMO this is a nice example of design similarity (difference) to other OOP languages like Java/C#/etc., i.e. in its own special PHP way (whenever it's for the good or for the worth).

~ Answered on 2012-05-06 18:28:41


Another option is to use the built in settype function:

$foo = "5bar"; // string
$bar = true;   // boolean

settype($foo, "integer"); // $foo is now 5   (integer)
settype($bar, "string");  // $bar is now "1" (string)

This actually performs a conversion on the variable unlike typecasting and allows you to have a general way of converting to multiple types.

~ Answered on 2011-03-07 12:38:59


As others have mentioned, objects need a __toString method to be cast to a string. An object that doesn't define that method can still produce a string representation using the spl_object_hash function.

This function returns a unique identifier for the object. This id can be used as a hash key for storing objects, or for identifying an object, as long as the object is not destroyed. Once the object is destroyed, its hash may be reused for other objects.

I have a base Object class with a __toString method that defaults to calling md5(spl_object_hash($this)) to make the output clearly unique, since the output from spl_object_hash can look very similar between objects.

This is particularly helpful for debugging code where a variable initializes as an Object and later in the code it is suspected to have changed to a different Object. Simply echoing the variables to the log can reveal the change from the object hash (or not).

~ Answered on 2016-08-31 21:21:50


Some, if not all, of the methods in the previous answers fail when the intended string variable has a leading zero, for example, 077543.

An attempt to convert such a variable fails to get the intended string, because the variable is converted to base 8 (octal).

All these will make $str have a value of 32611:

$no = 077543
$str = (string)$no;
$str = "$no";
$str = print_r($no,true);
$str = strval($no);
$str = settype($no, "integer");

~ Answered on 2014-05-19 08:09:54


I think this question is a bit misleading since, toString() in Java isn't just a way to cast something to a String. That is what casting via (string) or String.valueOf() does, and it works as well in PHP.

// Java
String myText = (string) myVar;

// PHP
$myText = (string) $myVar;

Note that this can be problematic as Java is type-safe (see here for more details).

But as I said, this is casting and therefore not the equivalent of Java's toString().

toString in Java doesn't just cast an object to a String. It instead will give you the String representation. And that's what __toString() in PHP does.

// Java
class SomeClass{
    public String toString(){
        return "some string representation";

// PHP
class SomeClass{
    public function __toString()
        return "some string representation";

And from the other side:

// Java
new SomeClass().toString(); // "Some string representation"

// PHP
strval(new SomeClass); // "Some string representation"

What do I mean by "giving the String representation"? Imagine a class for a library with millions of books.

  • Casting that class to a String would (by default) convert the data, here all books, into a string so the String would be very long and most of the time not very useful either.
  • To String instead will give you the String representation, i.e., only the name of the library. This is shorter and therefore gives you less, but more important information.

These are both valid approaches but with very different goals, neither is a perfect solution for every case and you have to chose wisely which fits better for your needs.

Sure, there are even more options:

$no = 421337  // A number in PHP
$str = "$no"; // In PHP, stuff inside "" is calculated and variables are replaced
$str = print_r($no, true); // Same as String.format();
$str = settype($no, 'string'); // Sets $no to the String Type
$str = strval($no); // Get the string value of $no
$str = $no . ''; // As you said concatenate an empty string works too

All of these methods will return a String, some of them using __toString internally and some others will fail on Objects. Take a look at the PHP documentation for more details.

~ Answered on 2018-12-21 11:08:38


The documentation says that you can also do:

$str = "$foo";

It's the same as cast, but I think it looks prettier.


~ Answered on 2013-11-15 22:45:49


You can always create a method named .ToString($in) that returns

$in . '';  

~ Answered on 2008-08-26 13:59:23


If you're converting anything other than simple types like integers or booleans, you'd need to write your own function/method for the type that you're trying to convert, otherwise PHP will just print the type (such as array, GoogleSniffer, or Bidet).

~ Answered on 2008-08-26 14:03:35


PHP is dynamically typed, so like Chris Fournier said, "If you use it like a string it becomes a string". If you're looking for more control over the format of the string then printf is your answer.

~ Answered on 2008-08-26 14:04:33


Double quotes should work too... it should create a string, then it should APPEND/INSERT the casted STRING value of $myVar in between 2 empty strings.

~ Answered on 2011-07-31 18:25:25


$parent_category_name = "new clothes & shoes";

// To make it to string option one
$parent_category = strval($parent_category_name);

// Or make it a string by concatenating it with 'new clothes & shoes'
// It is useful for database queries
$parent_category = "'" . strval($parent_category_name) . "'";

~ Answered on 2016-06-09 12:04:02


You can also use the var_export PHP function.

~ Answered on 2015-08-11 13:06:13


Try this little strange, but working, approach to convert the textual part of stdClass to string type:

$my_std_obj_result = $SomeResponse->return->data; // Specific to object/implementation

$my_string_result = implode ((array)$my_std_obj_result); // Do conversion

~ Answered on 2014-02-25 14:09:33


For objects, you may not be able to use the cast operator. Instead, I use the json_encode() method.

For example, the following will output contents to the error log:


~ Answered on 2013-04-03 17:44:36


__toString method or (string) cast

$string=(string)$variable;  //force make string 

you can treat an object as a string

class Foo

  public function __toString()
     return "foo";


echo new Foo(); //foo

also, have another trick, i assume i have int variable i want to make string it


~ Answered on 2020-10-12 17:53:28


I use variableToString. It handles every PHP type and is flexible (you can extend it if you want).

~ Answered on 2015-10-28 12:47:43

Most Viewed Questions: