给出一个像下面这样的基本对象,我的倾向(基于与AS3一起工作)是$friend
可以被解释为$this->friend
,但PHP解析器只将$friend
视为本地化到holler
函数的未初始化变量。有没有一种方法来访问成员变量不使用$this->
?我的目标是发现尽可能精简的语法。
class MyBuddy
{
private $friend = true;
public function holler()
{
if ( $friend ) // <- parser won't resolve $friend to a member variable
return 'Heeeeey Buuuuuday!';
else
return null;
}
}
Update:在考虑了给出的答案之后,似乎最简洁和易于理解的方法是通过引用将实例变量传递给函数顶部的函数级变量。对于引用详细实例变量的函数来说,这是一个不错的解决方案。
// Demonstrating a simple cache which abbreviates $this->thingCollection
// to $things for the function body
public function getThing( $id, $qty )
{
$things = &$this->thingCollection; // <-- pass by reference
if ( empty($things) )
$things = [];
if ( empty($things[$id]) )
$things[ $productId ] = [];
if ( empty($things[ $id ][ $qty ]) )
$things[ $id ][ $qty ] = get_thing_from_database( $id, $qty );
return $things[ $id ][ $qty ];
}
不要发明聪明的变通方法,因为在您之后维护代码的开发人员将很难理解。PHP的方法是使用$this,您应该遵循语言的惯例。
问题是php不认为它们是相同的,因此允许特定方法具有具有该属性名称的局部变量。例如:
class MyBuddy
{
private $friend = true;
public function holler($friend)
{
if ($this->friend == $friend ) // <- parser won't resolve $friend to a member variable
return 'Heeeeey Buuuuuday!';
else
return null;
}
}
define("HELL_NAW", false);
define("MMM_HMMM", true);
$hombre = new MyBuddy();
echo $hombre -> holler(HELL_NAW);
$l_jessie = new MyBuddy();
echo $l_jessie -> holler(MMM_HMMM);
所以要得到你想要的,你可以这样写:
public function holler()
{
$friend = $this ->friend;
if ($friend )
return 'Heeeeey Buuuuuday!';
else
return null;
}
但这可能被称为精益的反义词。但这也说明了一点(和Alex的),php并没有建立在你的责任原则的基础上,你最终会做更多的工作,使下一个家伙更难实现一个基于原则的目标,但对其他人来说似乎是美学的。
另一方面,php确实有__get()
和__set()
这两个神奇的方法,通过定义如何处理它们来允许引用未定义或不可访问的属性。这样,您就不需要引用$this->friend
,因为它不存在。只需引用该方法的参数(这很方便,但同样会使集群看起来很讨厌)。
我很同情你的问题,因为我差点就把它贴出来了。在这种情况下,你想做的事情对你来说更容易读懂,但对于另一个PHP开发人员来说,当目标是类级对象时,他们希望使用标准的$ This ->。