How to convert an object or variable to a string in PHP? Analogue of toString() from Java/.NET
Hello everyone! I'm new to PHP, coming from Java. In Java, I'm used to every object having a toString() method that can be called explicitly or implicitly (during string concatenation). For example:
```java
MyClass obj = new MyClass();
String text = "Value: " + obj.toString(); // or just + obj
```
In .NET it's the same — ToString() method.
In PHP I'm trying to do this:
```php
class User {
public $name = 'Anna';
}
$user = new User();
echo "Hello, " . $user; // Error: Object of class User could not be converted to string
```
Or I tried explicitly:
```php
echo $user->toString(); // Fatal error: Call to undefined method User::toString()
```
I understand that PHP doesn't have a built-in toString() method for all objects. How do I properly convert objects to a string?
No answers yet.
Log in to leave an answer
Blogs