PHP Class Error

I’m new to PHP Classes but I’ve been writing basic PHP code for awhile now. Basically I’m trying to learn OOP. I’m writing some code that isn’t working, it’s trying to call a method but giving me this error, " PHP Fatal error: Call to undefined method stdClass::has_attribute()". The method is there, it’s just giving me this error. I have included my php below, any help?

[php]

<?php require_once('database.php'); class Session { private $return_user=false; public $user_ip; function __construct() { session_start(); $_SESSION['user_ip'] = $_SERVER['REMOTE_ADDR']; $this->check_ip(); } public function is_returning_user() { return $this->return_user; } private function find_by_ip($user_ip=0) { $result_array = self::find_by_sql("SELECT * FROM user WHERE user_ip = '{$user_ip}' LIMIT 1"); return !empty($result_array) ? array_shift($result_array) : false; } 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; } private function check_ip() { $user_ip = $_SESSION['user_ip']; if(self::find_by_ip($user_ip) == true) { $this->user_ip = $_SESSION['user_ip']; $this->return_user = true; echo "RETURNING USER"; } else { unset($this->user_ip); $this->return_user = false; echo "NO RETURN"; } } private static function instantiate($record) { $object->last_name = $record['user_ip']; // More dynamic, short-form approach: foreach($record as $attribute=>$value){ if($object->has_attribute($attribute)) { $object->$attribute = $value; } } return $object; } public function has_attribute($attribute) { // get_object_vars returns an associative array with all attributes // (incl. private ones!) as the keys and their current values as the value $object_vars = get_object_vars($this); // We don't care about the value, we just want to know if the key exists // Will return true or false return array_key_exists($attribute, $object_vars); } } $session = new Session(); ?>

[/php]

I could be wrong but I think it’s due to calling a method before it’s created try reordering these methods:

[code]private static function instantiate($record) {
$object->last_name = $record[‘user_ip’];

    // More dynamic, short-form approach:
    foreach($record as $attribute=>$value){
      if($object->has_attribute($attribute)) {
        $object->$attribute = $value;
      }
    }
    return $object;
}
public function has_attribute($attribute) {
  // get_object_vars returns an associative array with all attributes 
  // (incl. private ones!) as the keys and their current values as the value
  $object_vars = get_object_vars($this);
  // We don't care about the value, we just want to know if the key exists
  // Will return true or false
  return array_key_exists($attribute, $object_vars);
}[/code]
Sponsor our Newsletter | Privacy Policy | Terms of Service