Forum Moderators: coopster

Message Too Old, No Replies

Accessing defined variables in object

         

sned

5:39 pm on Oct 21, 2008 (gmt 0)

10+ Year Member



So here's something I ran into today:

Say you define a "constant":

define('MY_TABLE', 'some_db_table_name');

Now, say you want to use that definition in an array or object:

$foo = $bar[MY_TABLE]; // this works fine
$foo = $bar->MY_TABLE; // this DOES NOT work!

Does anyone know how to access defined variables in objects?

Thanks!
-Sned

coopster

1:45 pm on Oct 22, 2008 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. For more information on scope, read the manual section on variable scope.

Constants [php.net]

If you are asking how to access them when they are defined in the class itself, you can check out Class Constants [php.net]

cameraman

2:12 pm on Oct 22, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Looks like braces work:
$foo = $bar->{MY_TABLE};

sned

3:50 pm on Oct 22, 2008 (gmt 0)

10+ Year Member



Ahh yes, the braces do the trick!

Thank you!
-sned

eelixduppy

4:08 pm on Oct 22, 2008 (gmt 0)



Sned, I've been wondering about this for a bit now. Why is it that you are using the constant as you have shown up above? It seems to defeat the purpose of having an object that way.

sned

4:16 pm on Oct 22, 2008 (gmt 0)

10+ Year Member



I've run into issues where people decide they don't like the naming scheme of the database, and go and change table names and field names.

So I've just started keeping one file for each project I work on (called something like definitions.php) which just defines all the table names and field names.

It's somewhat of a pain, doing queries like: "SELECT * FROM " . TABLENAME . " WHERE " . TABLEFIELD . " = '$val'", but it has already saved me a lot of time and effort when things change.

(Using the braces comes around when trying to get values from something like mysql_fetch_object, or getting at object data passed in a SOAP call, etc.)