note 101545 deleted from function.class-exists by danbrown
| From: | danbrown@php.net | Date: | Thu, 23 Dec 2010 16:26:44 +0000 |
| Subject: | note 101545 deleted from function.class-exists by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-175175@lists.php.net to get a copy of this message | ||
Note Submitter: contact at rahulprasad dot com
Reason: in docs
----
Declare a class only if does not exists.
------------------Example 1------------------
<?php
if(!class_exists('MyClass')) {
class MyClass {
public function __construct() {
echo "<br />Hello<br />";
}
}
}
$x = new MyClass();
?>
Output:
Hello
------------------Example 2------------------
<?php
class MyClass {
public function __construct() {
echo "<br />Hi<br />";
}
}
if(!class_exists('MyClass')) {
class MyClass {
public function __construct() {
echo "<br />Hello<br />";
}
}
}
?>
Output:
Hi
------------------Usage------------------
If any class is not supported in older version of PHP you can check it before creating it.
Like PHP version less than 5.1 does not support InvalidArgumentException class, So before using it
you can make sure it does exists but using class_exists()
<?php
if(!class_exists(InvalidArgumentException)) {
class InvalidArgumentException extends Exception {
}
}
?>