0

I recently upgraded Ubuntu from 20.04 LTS to 22.04 LTS. I noticed that PHP was upgraded to the following version:

PHP 8.1.2-1ubuntu2.13 (cli) (built: Jun 28 2023 14:01:49) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.2, Copyright (c) Zend Technologies
    with Zend OPcache v8.1.2-1ubuntu2.13, Copyright (c), by Zend Technologies

My PHP application stopped working in this part:

public function __set($name, $value)
{
  $this->$name = $value;
}

public function DisplayMenu($buttons)
{
  echo "\t\t\t<nav>\n\t\t\t\t<ul>\n";
  while (list($name, $url) = each($buttons)) {
    $this->DisplayButton($name, $url);
  }
  echo "\t\t\t\t</ul>\n\t\t\t</nav>\n";
}

The accessor magic method stopped working after the upgrade from PHP 7.x to 8.x. What is the new way to use the equivalent in PHP 8.x? Thank you.

Jaime Montoya
  • 6,915
  • 14
  • 67
  • 103
  • 2
    What error do you get? – ceejayoz Aug 17 '23 at 17:58
  • 2
    "stopped working" is not an adequate description of the problem for us to be able to help. What's the error? What _should_ it be doing? What is it doing instead? – Sammitch Aug 17 '23 at 18:00
  • @ceejayoz The HTML is printed out and when my `while` loop posted in the question starts, it stops working. It looks like the `each()` function was removed in PHP 8. – Jaime Montoya Aug 17 '23 at 18:04
  • @Sammitch The HTML is printed out and when my `while` loop posted in the question starts, it stops working. It looks like the `each()` function was removed in PHP 8. – Jaime Montoya Aug 17 '23 at 18:05
  • 2
    @JaimeMontoya "Stops working" should be accompanied by an error message in this situation. If you're not seeing one, you should check your error reporting and logs; life'll be tough without error messages. – ceejayoz Aug 17 '23 at 18:09
  • @ceejayoz You are right. I will try that next time for debugging properly. Thank you. – Jaime Montoya Aug 17 '23 at 18:10

1 Answers1

4

It's not the accessor. The problem is that the each function was removed in PHP 8. You'll need to switch to a foreach loop.

<?php
class what 
{
    public function __set($name, $value)
    {
        $this->$name = $value;
    }

    public function DisplayButton($name,$value)
    {
        $this->$name = $value;
    }

    public function DisplayMenu($buttons)
    {
      echo "\t\t\t<nav>\n\t\t\t\t<ul>\n";
      foreach( $buttons as $name => $url ) {
        $this->DisplayButton($name, $url);
      }
      echo "\t\t\t\t</ul>\n\t\t\t</nav>\n";
    }
}

$x = new what();
$x->DisplayMenu(['a'=>'b','c'=>'d']);
print_r($x);
?>
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30