Make PHP object different actions depending on variable name
For example, let's say I have a user database. I have a class that gets information from a database about these users.
I want to make the class "self-aware" of its own name, for example:
<?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 will change depending on what I named. Is it possible?
a source to share
Even if it is possible (I don't think so), you shouldn't. Others would just see a lot of magic and it would be difficult to debug. Stick to 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 be doing any blocking operations on the constructor):
$user = UserData::getById(24);
a source to share
Since a given object can have more than one name, this is not a common practice in modern programming languages. For example, if user 25 has a different name from user 24, what would you expect from the following code printed?
$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 force the object's constructor to accept a parameter that tells you which user you are dealing with, for example:
$user = new UserData(24);
echo 'Welcome, '.$user->name.'!';
a source to share
The relationship (for example, an object) to its variable name is one-to-many, that is, one value can have many names, where each is a reference to the same value. It may not even have any name, i.e. It can be an expression (a new expression, for example, returns an object). Therefore, it is not possible to determine the "name" of the software value. A value can have multiple names or names.
a source to share