tags:

views:

130

answers:

3

For example, if let's say I have a database of users. I have a class that gets information form the database about these users.

I want to make the class "self aware" of it's own name, like this:

<?php

class UserData {

//[code that fetches the ID number from the variable name, and queries the database for info]

}

$user24 = new UserData;
echo 'Welcome, '.$user24->name.'!';

?>

This code would, ideally, output something like "Welcome, Bob!", and would change depending on what I named it. Is this possible?

+6  A: 

Since a given object may have multiple names, this is not a generally valid technique in modern programming languages. For example, assuming user 25 has a different name from user 24, what would you expect the following code to print?

$user24 = new UserData;
echo 'Welcome, '.$user24->name.'!';
$user25 = $user24;
echo 'Welcome, '.$user25->name.'!';

Not only that, but you can have objects with no name:

echo 'Welcome, '.(new UserData)->name.'!';

A more typical implementation would have the object constructor take a parameter which tells it which user you're dealing with, like this:

$user = new UserData(24);
echo 'Welcome, '.$user->name.'!';
Greg Hewgill
+3  A: 

Even if it's possible (I don't think so), you shouldn't. Others would just see a lot of magic and it would be hard to debug. Stick to the standards and known ideas / patterns whenever possible.

Why don't you want to use:

$user = new UserData(24);

Or even better (because you shouldn't do any blocking operations in the constructor):

$user = UserData::getById(24);
viraptor
The second piece of code wouldn't work in PHP.
musicfreak
Ok, I corrected the static call syntax.
viraptor
Thanks, I didn't know that you could pass arguments to the __construct() function like that.
Bravery Onions
+1  A: 

A value (such as an object)'s relation to its variable name is one-to-many - that is, one value may have many names, where each of them is a reference to the same value. It may even have no name at all, ie, it could be an expression (a new expression, for example, returns an object). Therefore it is not possible to find out "the" name of a value programmatically. A value could have multiple names, or no names.

thomasrutter