Home > Backend Development > PHP Tutorial > Understanding the usage of php variable functions

Understanding the usage of php variable functions

怪我咯
Release: 2023-03-11 17:00:02
Original
1346 people have browsed it

Recently I saw a variable assigned a value from the name of a function as a string in a project. I thought the program was wrong, and I found out after asking my colleagues.

This is variable function, I'm sweating instantly. By the way, record it:

function func() {
  return 'hello,world!';
 }
$myFunction = 'func';
Copy after login

When we create a custom function and understand the usage of variable functions, in order to ensure that the function called by the program exists, we often first Use function_exists to determine whether the function exists.

The same method_exists can be used to detect whether a class method exists.

if (function_exists($myFunction )){
    echo 'exists';
}
Copy after login

Whether the class is defined, class_exists can be used.

class MyClass{
}
// 使用前检查类是否存在
if (class_exists('MyClass')) {
    $myclass = new MyClass();
}
Copy after login

There are many such checking methods in PHP, such as whether the file existsfile_existsetc.

$filename = 'test.txt';
if (!file_exists($filename)) {
    echo $filename . ' not exists.';
}
Copy after login

The above is the detailed content of Understanding the usage of php variable functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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