Use PHP functions in JavaScript

JavaScript get_class

Retrieves the class name

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
function get_class (obj) {
    // Retrieves the class name  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/get_class    // +   original by: Ates Goral (http://magnetiq.com)
    // +   improved by: David James
    // *     example 1: get_class(new (function MyClass() {}));
    // *     returns 1: "MyClass"
    // *     example 2: get_class({});    // *     returns 2: "Object"
    // *     example 3: get_class([]);
    // *     returns 3: false
    // *     example 4: get_class(42);
    // *     returns 4: false    // *     example 5: get_class(window);
    // *     returns 5: false
    // *     example 6: get_class(function MyFunction() {});
    // *     returns 6: false
    if (obj instanceof Object && !(obj instanceof Array) &&         !(obj instanceof Function) && obj.constructor &&
        obj != this.window) {
        var arr = obj.constructor.toString().match(/function\s*(\w+)/);
 
        if (arr && arr.length == 2) {            return arr[1];
        }
    }
 
    return false;}
external links: original PHP docs | raw js source

Examples

» Example 1

Running

1
get_class(new (function MyClass() {}));

Should return

1
"MyClass"

» Example 2

Running

1
get_class({});

Should return

1
"Object"

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 get_class 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
Kevin van Zonneveld
16 Feb '08 Permalink

q  @ David James: That's very nice to hear, and thank you for your contribution!

Gravatar
David James
15 Feb '08 Permalink

q  for get_class() I suggest adding the i flag to the regex to accomodate Function as well as function

BTW, i have convinced our lead programmer to adopt php.js as a standard library (and he's pretty picky)... great work!


Contribute a New function

More functions

In this category

class_alias
class_exists
» get_class
get_class_methods
get_class_vars
get_declared_classes
get_object_vars
method_exists
property_exists

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: Anonymous and Shawn Houser.
<your name here>

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