Solved

Catchable fatal error: Object of class Employee could not be converted to string in C:\wamp\www\phpvqp3_scripts\ch08\iterator-edit.php on line 33

Posted on 2014-03-09
3
941 Views
Last Modified: 2014-03-10
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Iterators</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<?php # Script 8.9 - iterator.php
//  This page defines and uses the Department and Employee classes. 

# ***** CLASSES ***** #

/* Class Department.
 *  The class contains two attribute: name and employees[].
 *  The class contains seven methods now! 
 */
class Department implements Iterator {
    private $_name;
    private $_employees;

    // For tracking iterations:
    private $_position = 0;
    
    function __construct($name) {
        $this->_name = $name;
        $this->_employees = array();
        $this->_position = 0;
    }
    function addEmployee(Employee $e) {
        $this->_employees[] = $e;
        foreach ($this->_employees as $name_them){
          echo '<br>name: '.$name_them;
        }
        echo "<p>{$e->getName()} has been added to the {$this->_name} department.</p>";
    }
    function __toString(){
      return $var;
    }

    // Required by Iterator; returns the current value:
    function current() {
        return $this->_employees[$this->_position];
    }

    // Required by Iterator; returns the current key:
    function key() {
        return $this->_position;
    }
    
    // Required by Iterator; increments the position:
    function next() {
        $this->_position++;
    }

    // Required by Iterator; returns the position to the first spot:
    function rewind() {
        $this->_position = 0;
    }

    // Required by Iterator; returns a Boolean indiating if a value is indexed at this position:
    function valid() {
        return (isset($this->_employees[$this->_position]));
    }
    
} // End of Department class.

class Employee {
    private $_name;
    function __construct($name) {
        $this->_name = $name;
    }
    function getName() {
        return $this->_name;
    }
} // End of Employee class.

# ***** END OF CLASSES ***** #

// Create a department:
$hr = new Department('Human Resources');
$film = new Department('last_time');
// Create employees:
$e1 = new Employee('Jane Doe');
$e2 = new Employee('John Doe');
$e3 = new Employee('amy');
// Add the employees to the department:
$hr->addEmployee($e1);
$hr->addEmployee($e2);
$hr->addEmployee($e3);
$film->addEmployee($e1);
// Loop through the department:
echo "<h2>Department Employees</h2>";
foreach ($hr as $e) {
    echo "<p>{$e->getName()}</p>";
}

// Delete the objects:
unset($hr, $e1, $e2);

?>
</body>
</html>

Open in new window


I edited larry ulman php tutorial because I want to loop through the employees


Catchable fatal error: Object of class Employee could not be converted to string in C:\wamp\www\phpvqp3_scripts\ch08\iterator-edit.php on line 33

I tried adding __tostring but can not add parameter
0
Comment
Question by:rgb192
3 Comments
 
LVL 31

Accepted Solution

by:
Marco Gasi earned 300 total points
ID: 39916793
    function addEmployee(Employee $e) {
        $this->_employees[] = $e;
        foreach ($this->_employees as $name_them){
          echo '<br>name: '.$name_them;
        }
        echo "<p>{$e->getName()} has been added to the {$this->_name} department.</p>";
    }

Open in new window


In the loop the variable $name_them reprsent the object 'employee' not a string, so if you try to echoe it you get that error. In addition, the function addEmployee is not a good place to iterate through all employees, but if you really want to do it you can use the original code thji way:

    function addEmployee(Employee $e) {
        $this->_employees[] = $e;
        foreach ($this->_employees as $name_them){
          echo '<br>name: '.$name_them->getName();
        }
        echo "<p>{$e->getName()} has been added to the {$this->_name} department.</p>";
    }

Open in new window

0
 
LVL 109

Assisted Solution

by:Ray Paseur
Ray Paseur earned 200 total points
ID: 39916883
In the bad old days of PHP, when you misapplied echo (or did other string castings that did not make sense) PHP tried to "help" by converting the non-string variables to a string representation of the data.  That's probably OK if the data happens to be a number; you can make some sense of the visual string representation of a number.  But what if the data structure doesn't make sense as a string?  Obvious examples are the complex data structures like arrays and objects.  In this case, PHP's ways of being "helpful" led to some really stupid and plainly erroneous output.  So PHP has changed the way it deals with this conundrum.

__toString() is one of the Magic Methods.  It allows a class to decide what data it will produce when it is treated like a string, such as with a casting assignment statement or an echo.
http://www.php.net/manual/en/language.oop5.magic.php

If you cannot modify the class definition to add the __toString() method, you can extend the class and put the __toString() method into the child class.  Then you would instantiate the child class.  The child will inherit all of the parent class methods and will provide the __toString() magic, returning the string representation your logic requires.

This makes a lot more sense than the other PHP ways of dealing with a complex-to-string conversion.  For an example of how dumb this can be, consider what happens when you convert an array to a string.  PHP returns the 5-character string "array" and raises a Notice.  So if you're running with the default error_reporting() level that suppresses Notice messages, you silently get a string that says "array" instead of anything that might make sense.  This is an example of why we want to use objects instead of arrays whenever it's feasible.  Even though you get a run-time failure from incorrect typecasting, at least you know and don't just get bogus data!
0
 

Author Closing Comment

by:rgb192
ID: 39917775
marco code allowed me to call method

I can relate to ray explanation because I tried to_string and I echo many times and see 'array'

thanks
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question