PHP.mk документација

class_exists

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.class-exists.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.class-exists.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
class_exists

Референца за `function.class-exists.php` со подобрена типографија и навигација.

function.class-exists.php

class_exists

(PHP 4, PHP 5, PHP 7, PHP 8)

class_existsПроверува дали класата е дефинирана

= NULL

class_exists(string $class, bool $autoload = true): bool

Оваа функција проверува дали дадената класа е дефинирана.

Параметри

class

Името на класата. Името се совпаѓа без да се води сметка за големи и мали букви.

autoload

Дали да autoload ако веќе не е вчитан.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true if class е дефинирана класа, false otherwise.

Примери

Пример #1 class_exists() example

<?php
// Check that the class exists before trying to use it
if (class_exists('MyClass')) {
$myclass = new MyClass();
}

?>

Пример #2 autoload пример за параметар

<?php
spl_autoload_register
(function ($class_name) {
include
$class_name . '.php';

// Check to see whether the include declared the class
if (!class_exists($class_name, false)) {
throw new
LogicException("Unable to load class: $class_name");
}
});

if (
class_exists(MyClass::class)) {
$myclass = new MyClass();
}

?>

Види Исто така

  • function_exists() - Вчитува PHP екстензија во време на извршување
  • enum_exists() - Проверува дали enum е дефиниран
  • interface_exists() - Проверува дали интерфејсот е дефиниран
  • get_declared_classes() - Враќа низа со името на дефинираните класи

Белешки од корисници 10 белешки

eiriks на hollowmatrix точка com
12 години пред
If you are using aliasing to import namespaced classes, take care that class_exists will not work using the short, aliased class name - apparently whenever a class name is used as string, only the full-namespace version can be used

use a\namespaced\classname as coolclass;

class_exists( 'coolclass' ) => false
info на ensostudio точка ru
пред 5 години
Note: class_exists() check only classes! 
<?php
interface DemoInterface {};
var_dump(class_exists('DemoInterface')); // false
trait DemoTrait {};
var_dump(class_exists('DemoTrait')); // false
class DemoClass {};
var_dump(class_exists('DemoClass')); // true
?>

Common function:
<?php
/**
  * Checks if the class/trait/interface has been defined.
  *
  * @param string $name The case-insensitive name of class/trait/interface
  * @param bool $autoload Whether to call spl_autoload()
  * @return bool
  */
function structure_exists(string $name, bool $autoload = true): bool
{
       return class_exists($name, $autoload)
              || interface_exists($name, $autoload)
              || trait_exists($name, $autoload);
}
?>
sb at firstvector dot org
пред 1 година
Beware that `\class_exists()` returns `true` for enums.

<?php
enum Test: int
{
    case One = 1;
    case Two = 2;
}

\var_dump(\class_exists(Test::class)); // bool(true)
?>

Having this in mind, the correct check for a class existence is:

<?php
function is_class_exist(string $class): bool
{
    return \class_exists($class) && !\enum_exists($class);
}
?>
rn at alpha9marketing dot com
пред 11 години
Beware: class_exists is case-INsensitive, as is class instantiation.

php > var_dump(class_exists("DomNode"));
bool(true)
php > var_dump(class_exists("DOMNode"));
bool(true)
php > var_dump(class_exists("DOMNodE"));
bool(true)
php > $x = new DOMNOdE();
php > var_dump(get_class($x));
string(7) "DOMNode"

(tested with PHP 5.5.10 on Linux)

This can cause some headaches in correlating class names to file names, especially on a case-sensitive file system.
Клаус
пред 15 години
If you recursively load several classes inside an autoload function (or mix manual loading and autoloading), be aware that class_exists() (as well as get_declared_classes()) does not know about classes previously loaded during the *current* autoload invocation.

Apparently, the internal list of declared classes is only updated after the autoload function is completed.
spam at wikicms dot org
12 години пред
Hi guys!
Be careful  and don't forget about second boolean argument $autoload (TRUE by default) when check exists class after spl_autoload_register. Propose short example
file second.php
<?php
class Second {}
?>
file index.php
<?php
class First
{
    function first($class, $bool) {
        spl_autoload_register( function($class) {
            require strtolower($class) . '.php';
        });
        echo class_exists($class, $bool)?'Exist!!!!':'Not exist!';
    }
}

new First($class = 'Second', $bool = true); //Exist!!!!
new First($class = 'Second', $bool = false); //Not exist!
?>
Because __autoload executing much earlier than boolean returned, imho..
richard на richard-sumilang точка com
пред 17 години
[ >= PHP 5.3]

If you are checking if a class exists that is in a specific namespace then you have to pass in the full path to the class:

echo (class_exists("com::richardsumilang::common::MyClass")) ? "Yes" : "No";
anonymous at somewhere dot tld
пред 22 години
If you have a directory of classes you want to create. (Modules in my instance)... you can do it like that

<?php
if (is_dir($this->MODULE_PATH) && $dh = opendir($this->MODULE_PATH)) {
   while (($file = readdir($dh)) !== false) {        
      if (preg_match("/(Mod[a-zA-Z0-9]+).php/", $file, $matches)>0) {                
         // include and create the class               
         require_once($this->MODULE_PATH."/".$file);
         $modules[] = new $matches[1]();
      }                
   }
} else {
   exit;
}
?>

//---
Here the rule is that all modules are on the form
ModModulename.php and that the class has the same name as the file.
The $modules array has all the classes initialized after this code
toocoolone at gmail dot com
пред 14 години
I'm running PHP 5.3.4 on Windows 7 and had some difficulty autoloading classes using class_exists(). In my case, when I checked for the class and it didn't exist, class_exists automatically threw a system Exception. I was also throwing my own exception resulting in an uncaught exception.

<?php
/**
 * Set my include path here
 */
$include_path = array( '/include/this/dir', '/include/this/one/too' );
set_include_path( $include_path );
spl_autoload_register();
/**
 * Assuming I have my own custom exception handler (MyException) let's
 * try to see if a file exists.
 */
try {
    if( ! file_exists( 'myfile.php' ) ) {
        throw new MyException('Doh!');
    }
    include( 'myfile.php' );
}
catch( MyException $e ) {
    echo $e->getMessage();
}
/**
 * The above code either includes myfile.php or throws the new MyException
 * as expected. No problem right? The same should be true of class_exists(), 
 * right? So then...
 */
$classname = 'NonExistentClass';
try {
    if( ! class_exists( $classname ) ) {
        throw new MyException('Double Doh!');
    }
    $var = new $classname();
}
catch( MyException $e ) {
    echo $e->getMessage();
}
/**
* Should throw a new instance of MyException. But instead I get an
* uncaught LogicException blah blah blah for the default Exception
* class AND MyException. I only catch MyException so we've got on
* uncaught resulting in the dreaded LogicException error.
*/
?>

By registering an additional autoload handler function that did nothing, I was able to stop throwing the extra Exception and only throw my own.

<?php
/**
 * Set my include path here
 */
$include_path = array( '/include/this/dir', '/include/this/one/too' );
set_include_path( $include_path );
spl_autoload_register();
spl_autoload_register( 'myAutoLoad' ); // Add these two and no worries...
function myAutoLoad() {}
/**
 * By registering the additional custom autoload function that does nothing
 * class_exists() returns only boolean and does NOT throw an uncaught Exception
 */
?>

Found this buried in some search results. I don't remember the page URL but if it would have been here it might have saved me some time!
Анонимен
1 месец пред
Beware that class_exists is a runtime check and not a compile time check!

This means that even if the class is defined after the class_exists, it will return true!

<?php

echo 'Does class "MyClass" exist? : ', class_exists('MyClass') ? 'YES' : 'NO';

class MyClass
{
}

?>

Output: YES
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.