我创建了一个用户类用下面的代码在非对象上:PHP OOP:调用一个成员函数
<?php
require_once("database.php");
class User {
public $id;
public $username;
public $password;
public $first_name;
public $last_name;
public static function find_all() {
return self::find_by_sql("select * from users");
}
public static function find_by_id($id=0) {
global $database;
$result_array=self::find_by_sql("Select * from users where id={$id} limit 1");
if (!empty($result_array)) {
return array_shift($result_array);
} else {
return FALSE;
}
}
public 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 function full_name() {
if (isset($this->first_name)&& isset($this->last_name)) {
return $this->first_name." ".$this->lastname;
} else {
return "";
}
}
private static function instantiate($record) {
$object=new self;
$object->id=$record['id'];
$object->username=$record['username'];
$object->password=$record['password'];
$object->first_name=$record['first_name'];
$object->last_name=$record['last_name'];
return $object;
}
}
?>
当我尝试在index.php来执行以下代码
<?php
$user=User::find_by_id(1);
echo $user->full_name();
?>
我得到以下错误:
(!) Fatal error: Call to a member function full_name() on a non-object in C:\wamp\www\imagepro\public\index.php on line 8
Call Stack
# Time Memory Function Location
1 0.0010 669408 {main}() ..\index.php:0
我不明白,因为我认为目的已经为什么我收到此错误实例化和错误说我从非对象调用对象函数。
我的PHP设置有问题,因为我在本地主机上运行它。谁能帮忙?
这就是我虽然也是,但似乎OP正在调用大量的静态函数来生成一个对象数组,所以返回值可以是一个对象。 – jeroen 2012-02-24 12:45:55