Use PHP functions in JavaScript

JavaScript constant

Given the name of a constant this function will return the constant's associated value

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
function constant (name) {
    // Given the name of a constant this function will return the constant's associated value  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/constant    // +   original by: Paulo Freitas
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: constant('IMAGINARY_CONSTANT1');
    // *     returns 1: null
    var clssPos = 0, clssCnst = null;    if ((clssPos = name.indexOf('::')) !== -1) {
        clssCnst = name.slice(clssPos+2);
        name = name.slice(0, clssPos);
    }
     if (this.window[name] === undefined) {
        return null;
    }
    if (clssCnst) {
        return this.window[name][clssCnst];    }
    return this.window[name];
}
external links: original PHP docs | raw js source

Examples

Running

1
constant('IMAGINARY_CONSTANT1');

Should return

1
null

Dependencies

No dependencies, you can use this function standalone.

Open syntax issues

php.js uses JsLint to help us keep our code consistent and prevent some common bugs.

Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.


Authors

Thanks to the following developers, you get to have constant goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Brett Zamir
Jun 21st Permalink

q  @Paulo: I think Kevin wants to avoid automatically importing PHP constants (whether as globals or on the namespaced object). If a user wants them, they can follow the notes at http://phpjs.org/functions/get_defined_constants:839 to get them in scope, but this function constant() could still be useful without them in the case of user-defined constants.

Gravatar
Paulo Freitas
Jun 19th Permalink

q  Hmm, this one should require get_defined_constants(), no? When I wrote I think that the get_defined_constants() doesn't exist yet, but for now it should be useful to do things like constant('DATE_W3C'). :)


Contribute a New function

More functions

In this category

» constant
define
defined
die
exit
pack
php_strip_whitespace
sleep
time_nanosleep
time_sleep_until
uniqid
usleep

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: @HalfWinter, Paulo Freitas, Andros Peña Romo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !