Home  >  Article  >  Backend Development  >  Understanding the usage of php variable functions

Understanding the usage of php variable functions

怪我咯
怪我咯Original
2017-06-28 09:53:311334browse

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';

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';
}

Whether the class is defined, class_exists can be used.

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

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.';
}

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!

Statement:
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