我一直使用对象——但我不会直接从查询中放入数据。使用“设置”函数我创建了布局,因此避免了连接和命名冲突的问题。在您的“full_name”示例中,我可能会使用“as”来获取名称部分,在对象中设置每个部分并提供“get_full_name”作为成员 fn。
如果你觉得雄心勃勃,你可以在“get_age”中添加各种东西。设置一次出生日期,然后从那里开始疯狂。
编辑:有几种方法可以从您的数据中制作对象。您可以预定义类并创建对象,也可以“即时”创建它们。
--> 一些简化的例子——如果这还不够,我可以添加更多。
即时:
$conn = DBConnection::_getSubjectsDB();
$query = "select * from studies where Status = 1";
$st = $conn->prepare( $query );
$st->execute();
$rows = $st->fetchAll();
foreach ( $rows as $row )
{
$study = (object)array();
$study->StudyId = $row[ 'StudyId' ];
$study->Name = $row[ 'StudyName' ];
$study->Investigator = $row[ 'Investigator' ];
$study->StartDate = $row[ 'StartDate' ];
$study->EndDate = $row[ 'EndDate' ];
$study->IRB = $row[ 'IRB' ];
array_push( $ret, $study );
}
预定义:
/** Single location info
*/
class Location
{
/** Name
* @var string
*/
public $Name;
/** Address
* @var string
*/
public $Address;
/** City
* @var string
*/
public $City;
/** State
* @var string
*/
public $State;
/** Zip
* @var string
*/
public $Zip;
/** getMailing
* Get a 'mailing label' style output
*/
function getMailing()
{
return $Name . "\n" . $Address . "\n" . $City . "," . $State . " " . $Zip;
}
}
用法:
$conn = DBConnection::_getLocationsDB();
$query = "select * from Locations where Status = 1";
$st = $conn->prepare( $query );
$st->execute();
$rows = $st->fetchAll();
foreach ( $rows as $row )
{
$location = new Location();
$location->Name= $row[ 'Name' ];
$location->Address = $row[ 'Address ' ];
$location->City = $row[ 'City' ];
$location->State = $row[ 'State ' ];
$location->Zip = $row[ 'Zip ' ];
array_push( $ret, $location );
}
然后你可以循环 $ret 并输出邮件标签:
foreach( $ret as $location )
{
echo $location->getMailing();
}