【发布时间】:2021-06-07 12:42:40
【问题描述】:
我想创建我的类的一个新实例,并将返回的值分配给它的属性。这样做的原因是我正在创建一系列从调用类继承的方法,而不是使用我已经工作过的静态方法。
我目前使用的示例:
public static function findById($id) {
$id = self::escapeParam($id);
$idVal = is_int($id) ? "i" : "s";
$sql = "SELECT * FROM ".static::$db_table." WHERE id = ? LIMIT 1";
return static::findByQuery($sql,$idVal,$id);
}
public static function findByQuery($sql,$bindChar = '',$bindVal = '') {
try {
$callingClass = get_called_class();
$object = new $callingClass;
$statement = Database::$connection->prepare($sql);
if(!empty($bindChar)) :
$statement->bind_param($bindChar, $bindVal);
endif;
if($statement->execute()) :
$result = $statement->get_result();
$object = $result->fetch_object();
endif;
$statement->close();
if(!empty($object)) :
return $object;
endif;
} catch(Exception $e) {
}
}
我尝试的是编写一个实例化方法来创建我的类的一个新实例,然后为对象的每个属性分配它从我所做的教程中的数组返回的值。但是,该教程已经过时了,并且没有使用任何新的语法或绑定,所以我试图重新编写它。
以下教程中的示例:
public static function find_by_id($id) {
global $database;
$the_result_array = static::find_by_query("SELECT * FROM " . static::$db_table . " WHERE id = $id LIMIT 1");
return !empty($the_result_array) ? array_shift($the_result_array) : false;
}
public static function find_by_query($sql) {
global $database;
$result_set = $database->query($sql);
$the_object_array = array();
while($row = mysqli_fetch_array($result_set)) {
$the_object_array[] = static::instantation($row);
}
return $the_object_array;
}
public static function instantation($the_record){
$calling_class = get_called_class();
$the_object = new $calling_class;
foreach ($the_record as $the_attribute => $value) {
if($the_object->has_the_attribute($the_attribute)) {
$the_object->$the_attribute = $value;
}
}
return $the_object;
}
private function has_the_attribute($the_attribute) {
return property_exists($this, $the_attribute);
}
我在本教程中尝试做的是使用一段时间将我的结果作为数组返回,然后通过将构建的数组传递给 static::instantation() 方法来分配一个变量,但它似乎从来没有工作正常,因为我在调用类(例如 Admin)中创建的任何公共函数都不会被调用,因为由于类没有被实例化,它们不存在。
【问题讨论】: