Home > Backend Development > PHP7 > body text

Differences between PHP5 and PHP7 regarding taking array elements as dynamic function names

藏色散人
Release: 2023-02-17 14:04:02
forward
2307 people have browsed it

When executing functions/methods by obtaining function/method names through variables in PHP5 and PHP7, the same code may not run due to different interpretation strategies between versions.

Example

$a = ['add', 'sub'];
 
class Test
{
  public function add()
  {
    echo 1 + 2;
  }
}
 
$t = new Test();
$t->$a[0]();
Copy after login

The above example can run normally under PHP5.6, but under PHP7 it will throw Fatal error: Function name must be a string. This is because when executing $t->$a0 under PHP5, $a[0] will be executed first, the element value will be obtained, and then the specific method of the object will be executed.

Under PHP7, $t->$a will be executed first, causing an error to be thrown and execution to be interrupted. If you need to execute it normally under PHP7, you need to modify it to $t->{$a[0]}().

For specific differences, please refer to:

Differences between PHP5 and PHP7 regarding taking array elements as dynamic function names

For more programming-related content, please pay attention to the php Chinese websiteIntroduction to Programmingcolumn!

The above is the detailed content of Differences between PHP5 and PHP7 regarding taking array elements as dynamic function names. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template