What is the PHP Equivalent of .NET/Java's toString()?

In this snippet, we will demonstrate to you how to find the PHP equivalent of .Net/Java’s toString.

We recommend you to apply type casting:

$myText = (string)$myVar;

Let’s take a look at an extensive example of using type casting:


class Cups
  public function __toString()
    return 'Ninety nine green cups';

$ex = new Cups();
var_dump($ex, (string) $ex);
// Returning: the instance of Cups and "Ninety nine green cups"

Watch a course Learn object oriented PHP

There you are. Above, we represented to you the shortest and the most efficient PHP equivalent to the .Net/Java’s toString.

What is Type Casting in PHP

Type Casting is aimed at using the variable value along with other data. That is to utilize a data type variable into another one.

So, type casting represents precise data type conversion. With it, the user specifies the data type to which intends to cast.

Take into consideration that PHP never requires or supports type definition of a variable. The variables automatically choose the data type on the basis of the context.