?
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
Medium Priority
?
963 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 31

Accepted Solution

by:
Marco Gasi earned 1200 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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 800 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

7 Extremely Useful Linux Commands for Beginners

Just getting started with Linux? Here's a quick start guide that has 7 commands that we believe will come in handy.

Question has a verified solution.

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

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

771 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