defined
Checks whether the given constant exists and is defined.
This function works also with class constants and enum cases.
Note:
If you want to see if a variable exists, use isset() as defined() only applies to constants. If you want to see if a function exists, use function_exists() .
Parameters
Return Values
Returns true if the named constant given by constant_name has been defined, false otherwise.
Examples
Example #1 Checking Constants
/* Note the use of quotes, this is important. This example is checking
* if the string ‘TEST’ is the name of a constant named TEST */
if ( defined ( ‘TEST’ )) echo TEST ;
>
interface bar const test = ‘foobar!’ ;
>
class foo const test = ‘foobar!’ ;
>
var_dump ( defined ( ‘bar::test’ )); // bool(true)
var_dump ( defined ( ‘foo::test’ )); // bool(true)
Example #2 Checking Enum Cases (as of PHP 8.1.0)
enum Suit
case Hearts ;
case Diamonds ;
case Clubs ;
case Spades ;
>
var_dump ( defined ( ‘Suit::Hearts’ )); // bool(true)
See Also
- define() — Defines a named constant
- constant() — Returns the value of a constant
- get_defined_constants() — Returns an associative array with the names of all the constants and their values
- function_exists() — Return true if the given function has been defined
- The section on Constants
User Contributed Notes 16 notes
My preferred way of checking if a constant is set, and if it isn’t — setting it (could be used to set defaults in a file, where the user has already had the opportunity to set their own values in another.)
defined ( ‘CONSTANT’ ) or define ( ‘CONSTANT’ , ‘SomeDefaultValue’ );
// Checking the existence of a class constant, if the class is referenced by a variable.
class Class_A
const CONST_A = ‘value A’;
>
// When class name is known.
if ( defined( ‘Class_A::CONST_A’ ) )
echo ‘Class_A::CONST_A defined’;
// Using a class name variable. Note the double quotes.
$class_name = Class_A::class;
if ( defined( «$class_name::CONST_A» ) )
echo ‘$class_name::CONST_A defined’;
// Using an instantiated object for a variable class.
$object_A = new $class_name();
if ( defined( get_class($object_A).’::CONST_A’ ) )
echo ‘$object_A::CONST_A defined’;
Before using defined() have a look at the following benchmarks:
true 0.65ms
$true 0.69ms (1)
$config[‘true’] 0.87ms
TRUE_CONST 1.28ms (2)
true 0.65ms
defined(‘TRUE_CONST’) 2.06ms (3)
defined(‘UNDEF_CONST’) 12.34ms (4)
isset($config[‘def_key’]) 0.91ms (5)
isset($config[‘undef_key’]) 0.79ms
isset($empty_hash[$good_key]) 0.78ms
isset($small_hash[$good_key]) 0.86ms
isset($big_hash[$good_key]) 0.89ms
isset($small_hash[$bad_key]) 0.78ms
isset($big_hash[$bad_key]) 0.80ms
PHP Version 5.2.6, Apache 2.0, Windows XP
Each statement was executed 1000 times and while a 12ms overhead on 1000 calls isn’t going to have the end users tearing their hair out, it does throw up some interesting results when comparing to if(true):
1) if($true) was virtually identical
2) if(TRUE_CONST) was almost twice as slow — I guess that the substitution isn’t done at compile time (I had to double check this one!)
3) defined() is 3 times slower if the constant exists
4) defined() is 19 TIMES SLOWER if the constant doesn’t exist!
5) isset() is remarkably efficient regardless of what you throw at it (great news for anyone implementing array driven event systems — me!)
May want to avoid if(defined(‘DEBUG’)).
You can use the late static command «static::» withing defined as well. This example outputs — as expected — «int (2)»
abstract class class1
<
public function getConst ()
<
return defined ( ‘static::SOME_CONST’ ) ? static:: SOME_CONST : false ;
>
>
final class class2 extends class1
<
const SOME_CONST = 2 ;
>
var_dump ( $class2 -> getConst ());
?>
Php check if undefined method
Create a separate file to test with to remove any other stuff that may be causing confusion DC Ignoring charles unnecessary downvote Another way to test this is to go into Card.php and add or ammend the constructor for Date This will then print when you are creating the date object if it doesnt print then you know you are instantiating a different Date object. If the getter contains particularly heavy processing (e.g. a database lookup or API call), you might want to factor in ways to avoid performing it twice, but that’s a bit out of scope.
«Call to undefined method»
echo " author->last> date->shortYear()> . ";
Fatal error: Call to undefined method Date::shortYear() in /f5/debate/public/libs/Card.php on line 22
Even though in Date.php (which is included in Card.php):
You’re instantiating the wrong Date class. You can use PHP’s get_class_methods() function to confirm which methods are available.
If you work in an setup where you automatically upload your changes from your IDE to the web server your checking your pages on. It might accidentally be the case that it didn’t upload the file.
there is a Date class in php. So my guess is you are instantiating the wrong Date class.
Change the name of the Date class in Card.php to say myDate;
Then try again $this->date = new myDate;
Create a separate file to test with to remove any other stuff that may be causing confusion
Ignoring charles unnecessary downvote
Another way to test this is to go into Card.php and add or ammend the constructor for Date
This will then print when you are creating the date object if it doesnt print then you know you are instantiating a different Date object.
Another method I often use is
$this->date = new Date; var_dump($this->date);
If it shows a differnt class structure then you are expecting then again you have the wrong Date object
If not then look to see if $this->date is not redefined anywhere
$this->date = new Date; . $this->date = new DateTime;
I know this is an old question, but I just battled this a bit.
I’m using Netbeans to code on a remote server, it turns out that for one reason or another, it wasn’t syncing a file to the remote host.
This was particularly annoying because I could ctrl-click into the class and see the method, and stepping into a different method in the same class would open up the seemingly correct file.
After I discovered the issue, I simply right clicked the file and clicked ‘upload.’
How to distinguish if a PHP property is undefined or set to NULL, class UNDEFINED ; class Test ; function __construct( $a=» ) ; function isDefined()
PHP: Detect «undefined function»-type errors before runtime?
Is there any tool that will help detect potential errors like «undefined function» in a PHP script before runtime?
If you ask the PHP command line interface to check that for syntax errors, it responds that there are none. But of course the script will fail if you try to run it, because there’s no function called «zarfnutz».
I understand that if the language is self-referential enough, it’s literally not possible to create such a tool which is guaranteed accurate (I don’t know if PHP is in fact self-referential enough). But in any case, there could definitely be a tool that could at least warn you that «zarfnutz» might be undefined, and such a tool would be very helpful to me.
I believe this is one of the features of PHPLint.
Well, I don’t know of a tool to do it, but function_exists and get_defined_functions are part of the PHP core.
Run php on the file with the lint flag (syntax check only):
A way to check is to use function_exists() . It’s not quite as flexible as checking via php -l, but it will get the job done.
Laravel Call to undefined method. Method exists, Check what dd returns in this -> $shop = new Shop($product);. Edit : Ok ,maybe namespace has a problem try : use App\Shop as MyShop;. Then
Check for undefined PHP method before calling?
What can I use other than if(!empty( $product->a_funky_function() )) to check if the method is empty before calling it?
I’ve tried method_exists() and function_exists() and a whole plethora of conditions. I think the issue is that I need to have my $product variable there.
A fairly common pattern is to have two methods on your class, along the lines of getField and hasField . The former returns the value, and the latter returns true or false depending whether or not the value is set (where «set» can mean not null, or not empty, or whatever else you might want it to mean).
class Foo < /** @var string */ private $field; /** * @return string */ public function getField() < return $this->field; > /** * @return bool */ public function hasField() < return $this->getField() !== null; > >
This would then be used like:
Often, like in this example, the has. method often just delegates to the get. method internally, to save duplicating the logic. If the getter contains particularly heavy processing (e.g. a database lookup or API call), you might want to factor in ways to avoid performing it twice, but that’s a bit out of scope.
You need absolutely to call it so it can compute the value which it will return, so I think there is no other way to know if it will return something not empty without calling it.
$result = $product->getFunction(); if(!empty($result)) < //your code here >