Php if method defined

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

Читайте также:  Python regexp телефона номера

// 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 Functions

PHP has more than 1000 built-in functions, and in addition you can create your own custom functions.

PHP Built-in Functions

PHP has over 1000 built-in functions that can be called directly, from within a script, to perform a specific task.

Please check out our PHP reference for a complete overview of the PHP built-in functions.

PHP User Defined Functions

Besides the built-in PHP functions, it is possible to create your own functions.

  • A function is a block of statements that can be used repeatedly in a program.
  • A function will not execute automatically when a page loads.
  • A function will be executed by a call to the function.
Читайте также:  Source code examples in java

Create a User Defined Function in PHP

A user-defined function declaration starts with the word function :

Syntax

Note: A function name must start with a letter or an underscore. Function names are NOT case-sensitive.

Tip: Give the function a name that reflects what the function does!

In the example below, we create a function named «writeMsg()». The opening curly brace ( < ) indicates the beginning of the function code, and the closing curly brace ( >) indicates the end of the function. The function outputs «Hello world!». To call the function, just write its name followed by brackets ():

Example

writeMsg(); // call the function
?>

PHP Function Arguments

Information can be passed to functions through arguments. An argument is just like a variable.

Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

The following example has a function with one argument ($fname). When the familyName() function is called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs several different first names, but an equal last name:

Example

familyName(«Jani»);
familyName(«Hege»);
familyName(«Stale»);
familyName(«Kai Jim»);
familyName(«Borge»);
?>

The following example has a function with two arguments ($fname and $year):

Example

function familyName($fname, $year) echo «$fname Refsnes. Born in $year
«;
>

familyName(«Hege», «1975»);
familyName(«Stale», «1978»);
familyName(«Kai Jim», «1983»);
?>

PHP is a Loosely Typed Language

In the example above, notice that we did not have to tell PHP which data type the variable is.

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a «Fatal Error» if the data type mismatches.

In the following example we try to send both a number and a string to the function without using strict :

Читайте также:  Python function returning tuple

Example

function addNumbers(int $a, int $b) return $a + $b;
>
echo addNumbers(5, «5 days»);
// since strict is NOT enabled «5 days» is changed to int(5), and it will return 10
?>

To specify strict we need to set declare(strict_types=1); . This must be on the very first line of the PHP file.

In the following example we try to send both a number and a string to the function, but here we have added the strict declaration:

Example

function addNumbers(int $a, int $b) return $a + $b;
>
echo addNumbers(5, «5 days»);
// since strict is enabled and «5 days» is not an integer, an error will be thrown
?>

The strict declaration forces things to be used in the intended way.

PHP Default Argument Value

The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:

Example

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

PHP Functions — Returning values

To let a function return a value, use the return statement:

Example

PHP Return Type Declarations

PHP 7 also supports Type Declarations for the return statement. Like with the type declaration for function arguments, by enabling the strict requirement, it will throw a «Fatal Error» on a type mismatch.

To declare a type for the function return, add a colon ( : ) and the type right before the opening curly ( < )bracket when declaring the function.

In the following example we specify the return type for the function:

Example

You can specify a different return type, than the argument types, but make sure the return is the correct type:

Example

Passing Arguments by Reference

In PHP, arguments are usually passed by value, which means that a copy of the value is used in the function and the variable that was passed into the function cannot be changed.

When a function argument is passed by reference, changes to the argument also change the variable that was passed in. To turn a function argument into a reference, the & operator is used:

Example

Use a pass-by-reference argument to update a variable:

Источник

Оцените статью