Thursday, 13 May 2021

Php: Convert an object to string

By implementing __toStirng() method in your class definition, you can specify how your object should be represented in string format.

 

If your class implements __toSting() method, you can conver object to string representation via type casting.

 

Example

$info = (string)$emp1;

 

to_string_demo.php

#!/usr/bin/php

<?php

   class Employee{
        var $id;
        var $first_name;
        var $last_name;
        var $country='India';

        function __toString(){
            return "Hello $this->first_name, you are from $this->country\n";
        }
   }

   $emp1 = new Employee;
   $emp1 -> id = 1;
   $emp1 -> first_name = 'Krishna';
   $emp1 -> last_name = 'Gurram';
   
   $info = (string)$emp1;
   echo $info;
?>

 

Output

$./to_string_demo.php 

Hello Krishna, you are from India

 

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment