Trying to visualize what is taking place with the following php code

Hi everyone, I have some php code that I would like to share with you. I’m trying to visualize what is actually taking place with the instantiate method below. All the code works and I have more code but its just another class that has methods that perform like the mysql_fetch_array and the mysql_query. I get what the code does but I’m to visualize how it works if that makes any sense.

Thanks for any help, highly appreciated!

index.php: Here is just a few lines that I test it with.

$user = User::find_by_id(1);
echo $user->username;


    class User {
    	public $id;
    	public $username;
    	public $first_name;
    	public $last_name;
      	public static function find_by_sql($sql="") {
        	global $database;
        	$result_set = $database->query($sql);
        	$object_array = array();
        	while ($row = $database->fetch_array($result_set)) {
         		$object_array[] = self::instantiate($row);
       		return $object_array;
     	public static function find_by_id($id=0) {
        	$result_array = self::find_by_sql("SELECT * FROM users WHERE id={$id} LIMIT 1");
    		return !empty($result_array) ? array_shift($result_array) : false;
    	private static function instantiate($record) {
    		$object = new self;
    		foreach($record as $attribute => $value) {
    			if($object->has_attribute($attribute)) {
    				$object->$attribute = $value;
    		return $object;
    	private function has_attribute($attribute) {
    		$object_vars = get_object_vars($this);
    		return array_key_exists($attribute, $object_vars);

No offense I stop visualizing after I seen global $database in the script. :frowning:

why is that bad? these tutorials are pretty old. $database is just

$database = new MySQLDatabase();

any help would be highly appreciated thanks

I would use dependance injection than assigning a variable globally. Like passing the $database reference via the classes construct instead of globally inside the method there.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.