program story

PHP-클래스 내부에 상수 정의

inputbox 2020. 10. 14. 07:48
반응형

PHP-클래스 내부에 상수 정의


클래스 내에서 상수를 정의하고 클래스 컨텍스트에서 호출 될 때만 표시되도록하려면 어떻게해야합니까?

.... 같은 것 Foo::app()->MYCONSTANT;

(그리고 MYCONSTANT무시되기를 원하면 )


클래스 상수 참조 :

class MyClass
{
    const MYCONSTANT = 'constant value';

    function showConstant() {
        echo  self::MYCONSTANT. "\n";
    }
}

echo MyClass::MYCONSTANT. "\n";

$classname = "MyClass";
echo $classname::MYCONSTANT. "\n"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::MYCONSTANT."\n"; // As of PHP 5.3.0

이 경우 MYCONSTANT자체적으로 에코 는 정의되지 않은 상수에 대한 알림 을 표시하고 문자열로 변환 된 상수 이름을 출력 합니다 : "MYCONSTANT".


편집 -아마도 당신이 찾고있는 것은이 정적 속성 / 변수입니다 .

class MyClass
{
    private static $staticVariable = null;

    public static function showStaticVariable($value = null)
    {
        if ((is_null(self::$staticVariable) === true) && (isset($value) === true))
        {
            self::$staticVariable = $value;
        }

        return self::$staticVariable;
    }
}

MyClass::showStaticVariable(); // null
MyClass::showStaticVariable('constant value'); // "constant value"
MyClass::showStaticVariable('other constant value?'); // "constant value"
MyClass::showStaticVariable(); // "constant value"

이것은 오래된 질문이지만 이제 PHP 7.1에서는 지속적인 가시성을 정의 할 수 있습니다.

<?php
class Foo {
    // As of PHP 7.1.0
    public const BAR = 'bar';
    private const BAZ = 'baz';
}
echo Foo::BAR.PHP_EOL;
echo Foo::BAZ.PHP_EOL;
?>

PHP 7.1에서 위 예제의 출력 :



치명적인 오류 : 포착되지 않은 오류 :…에서 private const Foo :: BAZ에 액세스 할 수 없습니다.

Note: As of PHP 7.1.0 visibility modifiers are allowed for class constants.

More info here


class Foo {
    const BAR = 'baz';
}

echo Foo::BAR;

This is the only way to make class constants. These constants are always globally accessible via Foo::BAR, but they're not accessible via just BAR.

To achieve a syntax like Foo::baz()->BAR, you would need to return an object from the function baz() of class Foo that has a property BAR. That's not a constant though. Any constant you define is always globally accessible from anywhere and can't be restricted to function call results.


This is a pretty old question, but perhaps this answer can still help someone else.

You can emulate a public constant that is restricted within a class scope by applying the final keyword to a method that returns a pre-defined value, like this:

class Foo {

    // This is a private constant
    final public MYCONSTANT()
    {
        return 'MYCONSTANT_VALUE';
    }
}

The final keyword on a method prevents an extending class from re-defining the method. You can also place the final keyword in front of the class declaration, in which case the keyword prevents class Inheritance.

To get nearly exactly what Alex was looking for the following code can be used:

final class Constants {

    public MYCONSTANT()
    {
        return 'MYCONSTANT_VALUE';
    }
}

class Foo {

    static public app()
    {
        return new Constants();
    }
}

The emulated constant value would be accessible like this:

Foo::app()->MYCONSTANT();

You can define a class constant in php. But your class constant would be accessible from any object instance as well. This is php's functionality. However, as of php7.1, you can define your class constants with access modifiers (public, private or protected).

A work around would be to define your constant as private or protected and then make them readable via a static function. This function should only return the constant values if called from the static context.

You can also create this static function in your parent class and simply inherit this parent class on all other classes to make it a default functionality.

Credits: http://dwellupper.io/post/48/defining-class-constants-in-php

참고URL : https://stackoverflow.com/questions/5892226/php-define-constant-inside-a-class

반응형