嗨,我对OOP PHP还比较陌生,正在尝试了解一些概念。我有两种方法,一种是公共方法,另一种是私人方法。
public函数is参数由get值填充,然后使用private方法查询数据库。
public function viewProject($id) {
if (!intval($id)) {
$this->projectError = 'The requested project must be a numeric value';
return false;
}
if (!$this->findProject($id)) {
$this->projectError = 'The specified project was not found.';
return false;
}
return true;
}
private function findProject($pid) {
$data = $this->_db->get("projects", array('id', "=", $pid));
return $data->results();
}
我希望能够将findProject方法的结果存储在类似var的中
$this->projectName=//此处的结果用于名称
但是,我不完全确定如何在公共方法中访问查询的结果。
一个类的所有poperties,public、protected和private,都可以在该类的每个方法中访问。如果将projectName定义为(私有)属性,则可以在其他所有方法中访问它。
此外,您的查询结果可能是一个多维数组,因此您必须自己从结果中检索projectName值。
class A
{
protected $projectName;
public function viewProject($id) {
if (!intval($id)) {
$this->projectError = 'The requested project must be a numeric value';
return false;
}
$results = $this->findProject($id);
if (!$results) {
$this->projectError = 'The specified project was not found.';
return false;
}
//Parse results
//assuming $this->_db->get() returns a multi-dimensional array
//assuming 'projectName' corresponds is the db column name
$this->projectName = $results[0]['projectName'];
return true;
}
private function findProject($pid) {
$data = $this->_db->get("projects", array('id', "=", $pid));
return $data->results();
}
}
尝试
public function viewProject($id) {
if (!intval($id)) {
$this->projectError = 'The requested project must be a numeric value';
return false;
}
$this->$project = $this->findProject($id); //project has the value
if (!$project) {
$this->projectError = 'The specified project was not found.';
return false;
}
return true;
}
private function findProject($pid) {
$data = $this->_db->get("projects", array('id', "=", $pid));
return $data->results();
}
希望它能有所帮助:)