[php] PHP - define constant inside a class

How can I define a constant inside a class, and make it so it's visible only when called in a class context?

....something like Foo::app()->MYCONSTANT;

(and if called like MYCONSTANT to be ignored)

This question is related to php class constants

The answer is


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


This is and old question, but now on PHP 7.1 you can define constant visibility.

EXAMPLE

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

Output of the above example in PHP 7.1:

bar

Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …

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();

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to constants

Constants in Kotlin -- what's a recommended way to create them? Why Is `Export Default Const` invalid? Proper use of const for defining functions in JavaScript Declaring static constants in ES6 classes? How can I get the size of an std::vector as an int? invalid use of non-static member function Why does JSHint throw a warning if I am using const? Differences Between vbLf, vbCrLf & vbCr Constants Constant pointer vs Pointer to constant Const in JavaScript: when to use it and is it necessary?