Php 原则:如何引用带有箭头(';-&>;';)符号的模型属性?
根据原则,我应该能够使用箭头符号(Php 原则:如何引用带有箭头(';-&>;';)符号的模型属性?,php,doctrine,Php,Doctrine,根据原则,我应该能够使用箭头符号($record->myField)或数组符号($record['myField'])引用模型的属性,只要模型是从记录类派生的 我使用Doctrine从数据库生成模型,因此我有一个(生成的)Recipe类,它扩展了BaseRecipe类,该类扩展了Doctrine\u记录。实例化配方对象后,我可以使用数组表示法访问其值,但使用箭头表示法只返回空值。我错过了什么 由条令生成的BaseRecipe类有两种方法: public function setTableDefi
$record->myField
)或数组符号($record['myField']
)引用模型的属性,只要模型是从记录
类派生的
我使用Doctrine从数据库生成模型,因此我有一个(生成的)Recipe
类,它扩展了BaseRecipe
类,该类扩展了Doctrine\u记录
。实例化配方
对象后,我可以使用数组表示法访问其值,但使用箭头表示法只返回空值。我错过了什么
由条令生成的BaseRecipe类有两种方法:
public function setTableDefinition()
{
$this->setTableName('rcp_recipe');
$this->hasColumn('recipe_id', 'integer', 4, array(
'type' => 'integer',
'fixed' => 0,
'unsigned' => false,
'primary' => true,
'autoincrement' => true,
'length' => '4',
));
...
}
public function setUp()
{
parent::setUp();
$this->hasMany('RcpTime', array(
'local' => 'time_id',
'foreign' => 'time_id'));
...
}
下面是我如何使用它的:
$newRecipes = RecipeService::getLatestRecipes();
foreach ($newRecipes as $recipe)
{
echo($recipe['title']); // prints the expected value
echo($recipe->title); // prints empty string
}
下面是我的getLatestRecipes
方法:
static function getLatestRecipes() {
$q = Doctrine_Query::create()
->from('Recipe')
->orderBy('recipe_id desc')
->limit(5);
return $q->fetchArray();
}
这就是问题所在;)
换成
static function getLatestRecipes() {
$q = Doctrine_Query::create()
->from('Recipe')
->orderBy('recipe_id desc')
->limit(5);
return $q->execute();
}
您将得到一个对象,它使您能够使用“箭头”
使用[]从数组中获取属性,使用->从对象中获取属性。由于您的方法返回一个数组->不起作用
不过,您应该收到一条错误消息。(“试图从非对象获取属性”或类似的内容)
在您仍在开发时设置
错误报告(E\u ALL)
。我们可以看到代码吗?BaseRecipe是否有_构造()或BaseRecipe()方法?没有其他错误消息?如何实例化对象?@tilman:添加了一些代码。没有错误消息,只是返回了一个空字符串。(旁注)这就成功了,谢谢你的正确答案和很好的解释!如果您只需要该查询的实际数据,我建议使用数组
static function getLatestRecipes() {
$q = Doctrine_Query::create()
->from('Recipe')
->orderBy('recipe_id desc')
->limit(5);
return $q->execute();
}