w3resource

PHP OOP: Class with magic method


10. Person Class with __toString()

Write a PHP class called 'Person' with properties like 'name' and 'age'. Implement the '__toString()' magic method to display person information.

Sample Solution:

PHP Code :

<?php
 class Person {
    private $name;
    private $age;

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

    public function __toString() {
        return "Name: " . $this->name . "</br>" .
               "Age: " . $this->age . "</br>";
    }
}

$person = new Person("Natalius Esther", 30);
echo $person;

?>

Sample Output:

Name: Natalius Esther
Age: 30

Explanation:

In the above exercise -

  • The Person class has two private properties: $name and $age, which represent the person's name and age.
  • The constructor method __construct() is used to initialize the values of the properties when creating a new instance of the Person class.
  • The __toString() magic method returns a string representation of the person's information when the object is treated as a string. It combines name and age properties into a formatted string.

Flowchart:

Flowchart: Class with magic method.

For more Practice: Solve these Related Problems:

  • Write a PHP class that includes a __toString() method to return a formatted string of person details and test it with different inputs.
  • Write a PHP program to extend the Person class and override the __toString() method to include additional details such as occupation.
  • Write a PHP function to compare two Person objects based on their __toString() outputs.
  • Write a PHP script to instantiate multiple Person objects and concatenate their string representations for display.

Go to:


PREV : Animal Abstract Class.
NEXT : Employee Extending Person.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.