Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 994
  • Last Modified:

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

<!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
rgb192
Asked:
rgb192
2 Solutions
 
Marco GasiFreelancerCommented:
    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
 
Ray PaseurCommented:
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
 
rgb192Author Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now