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

defined

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

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

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

function.defined.php

defined

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

definedПроверува дали постои константа со даденото име

= NULL

defined(string $constant_name): bool

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

Оваа функција работи и со константи во класа and случаи на enum.

Забелешка:

Ако сакате да видите дали постои променлива, користете isset() as defined() се однесува само на constants. Ако сакате да видите дали постои функција, користете function_exists().

Параметри

constant_name

Име на константа.

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

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

Примери

Пример #1 Проверка на константи

<?php

/* 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)

?>

Пример #2 Проверка на Enum случаи (од PHP 8.1.0)

<?php

enum Suit
{
case
Hearts;
case
Diamonds;
case
Clubs;
case
Spades;
}

var_dump(defined('Suit::Hearts')); // bool(true)

?>

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

  • define() - Дефинира именувана константа
  • constant() - Враќа вредност на константа
  • get_defined_constants() - Враќа асоцијативна низа со имињата на сите константи и нивните вредности
  • function_exists() - Вчитува PHP екстензија во време на извршување
  • HTTP автентикација Константи

Белешки од корисници — Интерпретира стринг од XML во објект

daniel на neville dot tk
пред 17 години
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.)

<?php

defined('CONSTANT') or define('CONSTANT', 'SomeDefaultValue');

?>

Dan.
Tr909 at com dot nospam dot bigfoot
пред 8 години
// 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';
Ларс Лернестал
пред 14 години
if you want to check id a class constant is defined use self:: before the constant name:

<?php
defined('self::CONSTANT_NAME');
?>
tris+php на tfconsulting dot com dot au
пред 16 години
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'))...
r dot hartung на roberthartung dot de
пред 16 години
You can use the late static command "static::" withing defined as well. This example outputs - as expected - "int (2)"

<?php
  abstract class class1
  {
    public function getConst()
    {
      return defined('static::SOME_CONST') ? static::SOME_CONST : false;
    }
  }
  
  final class class2 extends class1
  {
    const SOME_CONST = 2;
  }
  
  $class2 = new class2;
  
  var_dump($class2->getConst());
?>
Шон Х
пред 17 години
I saw that PHP doesn't have an enum function so I created my own. It's not necessary, but can come in handy from time to time.

<?php
    function enum()
    {
        $args = func_get_args();
        foreach($args as $key=>$arg)
        {
            if(defined($arg))
            {
                 die('Redefinition of defined constant ' . $arg);
            }

            define($arg, $key);
        }
    }
    
    enum('ONE','TWO','THREE');
    echo ONE, ' ', TWO, ' ', THREE;
?>
passerbyxp на gmail dot com
пред 13 години
This function, along with constant(), is namespace sensitive. And it might help if you imagine them always running under the "root namespace":

<?php
namespace FOO\BAR
{
    const WMP="wmp";
    function test()
    {
        if(defined("WMP")) echo "direct: ".constant("WMP"); //doesn't work;
        elseif(defined("FOO\\BAR\\WMP")) echo "namespace: ".constant("FOO\\BAR\\WMP"); //works
        echo WMP; //works
    }
}
namespace
{
    \FOO\BAR\test();
}
louis на louisworks dot de
пред 7 години
Dont forget to put the name of your constant into single quotation mark. You will not get an error or a warning.

<?php
define("AMOUNT_OF_APPLES", 12);
if(defined(AMOUNT_OF_APPLES)){
   //you won't get an output here
   echo AMOUNT_OF_APPLES;
}
?>

so do instead

<?php
define("AMOUNT_OF_APPLES", 12);
if(defined("AMOUNT_OF_APPLES")){
   //here you go
   echo AMOUNT_OF_APPLES;
}

//output: 12
?>

It took me half an day to see it...
info на daniel-marschall dot de
пред 16 години
I found something out: defined() becomes probably false if a reference gets lost.

<?php

session_start(); // $_SESSION created
define('SESSION_BACKUP', $_SESSION);
if (defined('SESSION_BACKUP')) echo 'A';
session_unset(); // $_SESSION destroyed
if (defined('SESSION_BACKUP')) echo 'B';

?>

You will see "A", but not "B".
ndove на cox dot net
21 години пред
In PHP5, you can actually use defined() to see if an object constant has been defined, like so:

<?php

class Generic
{
    const WhatAmI = 'Generic';
}

if (defined('Generic::WhatAmI'))
{
    echo Generic::WhatAmI;
}

?>

Thought it may be useful to note.

-Nick
ohcc на 163 dot com
пред 5 години
If a constant's name has a leading backslash (\), it's not possible to detect its existence using the defined() function, or to get its value using the constant() function. 

You can check its existence and get its value using the get_defined_constants() function, or prepend 2 more backslashes (\\) to the constant's name.

<?php
    define('\DOMAIN', 'wuxiancheng.cn');
    $isDefined = defined('\DOMAIN'); // false
    $domain = constant('\DOMAIN'); // NULL, in Php 8+ you'll get a Fatal error.
    var_dump($isDefined, $domain);
?>

<?php
    define('\DOMAIN', 'wuxiancheng.cn');
    $constants = get_defined_constants();
    $isDefined = isSet($constants['\DOMAIN']);
    $domain = $isDefined ? $constants['\DOMAIN'] : NULL;
    var_dump($isDefined, $domain);
?>

<?php
    define('\DOMAIN', 'wuxiancheng.cn');
    $isDefined = defined('\\\DOMAIN');
    $domain = constant('\\\DOMAIN');
    var_dump($isDefined, $domain);
?>
vindozo на gmail dot com
пред 15 години
If you wish to protect files from direct access I normally use this:

index.php:

<?php
// Main stuff here
define('START',microtime());

include "x.php";
?>

x.php:

<?php
defined('START')||(header("HTTP/1.1 403 Forbidden")&die('403.14 - Directory listing denied.'));
?>
Анонимен
пред 8 години
Be careful with boolean defines and assuming a check is done for a specific value by defined such as
<?php

define('DEBUG', false);

if(defined('DEBUG')){
    echo 'Not really debugging mode';
}
?>

You want to also check the constant as in

<?php
define('DEBUG', true);

if(defined('DEBUG') && DEBUG){
    echo 'Really this is debugging mode';
}
?>

All defined is doing is verifying the constant exists not it's value.
Питер Френсен
пред 1 година
To check in a trait if a constant is defined in the class using the trait, prepend the constant name with `self::class`:

<?php

trait MyTrait {
  public function checkConstant() {
    assert(defined(self::class . "::MY_CONSTANT"));
    print self::MY_CONSTANT;
  }
}

class MyClass {
  use MyTrait;
  protected const MY_CONSTANT = 'my value';
}

$class = new MyClass();
$class->checkConstant();
?>
reachmike на hotpop точка com
пред 17 години
You may find that if you use <?= ?> to dump your constants, and they are not defined, depending on your error reporting level, you may not display an error and, instead, just show the name of the constant. For example:

<?= TEST ?>

...may say TEST instead of an empty string like you might expect. The fix is a function like this:

<?php

function C(&$constant) {
    $nPrev1 = error_reporting(E_ALL);
    $sPrev2 = ini_set('display_errors', '0');
    $sTest = defined($constant) ? 'defined' : 'not defined';
    $oTest = (object) error_get_last();
    error_reporting($nPrev1);
    ini_set('display_errors', $sPrev2);
    if ($oTest->message) {
        return '';
    } else {
        return $constant;
    }
}

?>

And so now you can do:

<?= C(TEST) ?>

If TEST was assigned with define(), then you'll receive the value. If not, then you'll receive an empty string.

Please post if you can do this in fewer lines of code or do something more optimal than toggling the error handler.
На оваа страница

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

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

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

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

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