Currently I’m working on converting my practice project, a simple uploader program in PHP, into OOP.
Let’s take a look at the construct of the User class. For every instance of the class that is created, there is a check on whether the parameter provided is an id or a username, simply by checking if it’s a string or an integer. If it’s an integer it supposes that the variable given is a user id, and so continues by filling up the other properties.
class User { private $mId; private $mName; ...... function __construct( $construct ) { if ( is_int( $construct ) ) { // mySQL query by user id $this->mId = $construct; ....... else { // mySQL query by username $this->mName = $construct; .......
In order to display the username which is a private property ($mName) I used a simple fuction
public function GetName() { return $this->mName; }
So in my index.php I used to following code to display the user who owned a specific folder:
$owner = New User( $folder_owner['id'] );
$folder_owner['id'] was part of an mySQL fetched array which carried the owner’s id.
However, when I called to my previous method to display the username:
echo $owner->GetName();
the result was echoing not the username as expected but instead the user’s id.
foo.txt, created on 12-06-2007 by 2
The class’s methods seem correct, so what was it that went wrong back there?
Let’s look again the creation of my new User object.
$owner = New User( $folder_owner['id'] );
As I said before, $folder_owner['id'] came from a mysql_fetch_array function. When this function is called, the array created from each row is always an array of strings. So even if the cell that contains the requested id in my db contains an integer, the result will always be extracted as a string. As my constructor received a string and not an integer, $this->mName was set with the variable provided, which in our case was in fact the id and not the username, but still had the form of a string. So, calling at the method GetName() would always return the id.
The error was pointed out by my friend and tutor Dionyziz, who also suggested me the simple solution of converting $folder_owner['id'] to an integer before using it as a parameter for my method.
$owner = New User( ( integer ) $folder_owner['id'] );
What will definitely not be forgotten:
- mysql_fetch_array() always returns an array of strings.
special thanks to Dionyziz for helping me out
More info: