我是一名PHP新手。我真的需要帮助。你能看到这里__get方法和getcount()方法的区别吗?我认为它们都在做同样的事情,但我想知道是否存在可见性或其他问题。我在分享代码。非常感谢!
protected $count = null;
protected $max = null;
public function getCount(){
$rs = mysql_query("select count(*) from ogrenci");
$count = mysql_ results($rs, 0, 0);
mysql_free_result($rs);
}
public function __get($name) {
if($name == 'count') {
if($this->count == null) {
$rs = mysql_query("select count(*) from ogrenci");
$count = mysql_ results($rs, 0, 0);
mysql_free_result($rs);
}
return $this->count;
}
else if ($name == 'max')
{
//some code
}
}
}
$o=new Ogrenci();
echo $o->count;
echo $o->getCount();
- 在
getCount()
中,您没有设置任何内容。你也没有返回任何东西,所以它不回显任何东西。 - 在
__get()
中,你返回$this->count
,但你没有在任何地方设置它,所以大概它不回任何东西。
也许你想要的地方:
$this->count = mysql_results($rs, 0, 0);
在这种情况下,getCount()
是一个自定义的专用方法,从ogrenci
开始计数。
__get()
属于魔法方法家族,它用于从不可访问的属性中读取数据。
您可以在文档http://php.net/manual/en/language.oop5.overloading.php#object.get中阅读更多关于magic method的信息
在PHP中你不应该使用__get
来计数,你应该保留getCount
方法