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
913 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 30

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 108

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Both Easy and Powerful How easy is PHP? http://lmgtfy.com?q=how+easy+is+php (http://lmgtfy.com?q=how+easy+is+php)  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
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 …

706 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now