Home > Backend Development > PHP Problem > How to determine whether a class exists in php

How to determine whether a class exists in php

青灯夜游
Release: 2023-03-15 08:12:02
Original
3813 people have browsed it

In PHP, you can use the class_exists() function to determine whether the specified class exists. The function of this function is to check whether the class has been defined. The syntax is "class_exists('class name')"; if the specified class If it has been defined (exists), it returns true, otherwise it returns false.

How to determine whether a class exists in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

In php, you can use the class_exists() function To determine whether the specified class exists.

The class_exists() function can check whether the specified class has been defined.

Syntax:

class_exists(string $class, bool $autoload = true): bool
Copy after login
  • class: class name. Name matching is case-insensitive.

  • autoload: Whether to call __autoload by default.

Return value:

  • If the class pointed to by class has been defined, this function returns true , otherwise return false.

Example 1: Check whether class HelloWorld has been defined

<?php
   if (class_exists(&#39;HelloWorld&#39;)) {
      $helloworld = new HelloWorld();
   }
?>
Copy after login

class_exists() will try to call _autoload by default, if you don’t want class_exists() When calling _autoload, you can set the autoload parameter to FALSE.

Example 2: autoload parameter example

<?php
function __autoload($class)
{
    include($class . &#39;.php&#39;);

    // Check to see if the include declared the class
    if (!class_exists($class, false)) {
        trigger_error("Unable to load class: $class", E_USER_WARNING);
    }
}

if (class_exists(&#39;MyClass&#39;)) {
    $myclass = new MyClass();
}

?>
Copy after login

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to determine whether a class exists in php. For more information, please follow other related articles on the PHP Chinese website!

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