Lex
Lex

Reputation: 57

Catchable fatal error: Object of class dayDaytimeFields could not be converted to string

I am trying to render a part of a table using a self created object. When trying to access the method in the class I get:

Catchable fatal error: Object of class dayDaytimeFields could not be converted to string in /Applications/MAMP/[...]/test.php on line 85

Line 85 is:

$testObj->renderFields();

This is my code:

<table class="table table-striped table-bordered table-hover">
  <caption>Week Planner</caption>
  <thead>
    <tr>
      <th></th>
      <th>Breakfast</th>
      <th>Lunch</th>
      <th>Dinner</th>
    </tr>
  </thead>
  <tbody>

    <?php
        class dayDaytimeFields {

            public $dayDaytime;

            public $week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
            public $weekShort = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

            public $dayTime = ['Breakfast', 'Lunch', 'Dinner'];
            public $dayTimeShort = ['BrF', 'Lun', 'Din'];

            public function renderFields() {

                for ($i = 0; $i < count($this->$week); $i++) {

                    echo "<tr><th>" . $this->$week[$i] . "</th>";

                    for ($j = 0; $j < count($this->$dayTime); $j++) {
                        $this->dayDaytime = $this->$weekShort[$i] . $this->$dayTimeShort[$j];
                        echo "<td><input type='text' name='" . $this->dayDaytime . "' id='" . $this->dayDaytime . "'></td>";
                    }

                    echo "</tr>";
                }
            }
        }
    ?>

    <?= 
      $testObj = new dayDaytimeFields();
      $testObj->renderFields(); 
    ?>

  </tbody>
</table>         

This is my first step into OOP, so any further input (i.e. how to improve the code) is highly appreciated :-)

Upvotes: 2

Views: 281

Answers (1)

Darragh Enright
Darragh Enright

Reputation: 14136

You have a problem here:

<?= 
  $testObj = new dayDaytimeFields();
  $testObj->renderFields(); 
?>

First of all, the <?= tag is shorthand for:

<?php echo

So you are essentially doing this:

<?php echo $testObj = new dayDaytimeFields(); ?> 

Which is triggering your catchable fatal error; your class dayDaytimeFields obviously does not have a __toString() method so you cannot automatically echo it.

Actually, it would be more accurate to say that your code is being interpreted like this:

<?php echo $testObj = new dayDaytimeFields(); $testObject->renderFields(); ?>

If you implemented a __toString() method, it would be called and its return value would be printed.

However, the second statement $testObject->renderFields() would be called but its value would not be echoed.

Do this instead, assuming that you want to echo the return value from $testObj->renderFields():

<?php

$testObj = new dayDaytimeFields();
echo $testObj->renderFields(); 

// etc.

Hope this helps :)

Upvotes: 3

Related Questions