[英]Is it possible to call a function within a constructor? PHP
是否可以在构造函数中调用函数?
例如:
class Foo
{
public $bars = array();
public function __construct($string)
{
fetchBars($string);
}
public function fetchBars($string)
{
$folder = opendir($string);
while (false !== ($bar = readdir($folder)))
{
$this->bars[] = $bar;
}
closedir($folder);
}
}
我展示的例子不起作用。 我试图找出是否可以在构造函数中使用函数,但我找不到 awnser。 我知道我可以在构造函数中硬编写函数,但是我最终得到了双重代码。 如果没有其他选择,我会这样做,但如果有其他选择,请随时分享您的知识!
提前致谢!
亲切的问候
是的,这是可能的,但是除非函数是全局的并且在任何类之外,否则您需要使用 $this 关键字。
class Foo
{
public $bars = array();
public function __construct($string)
{
$this->fetchBars($string);
myfunction(); // this can be called without $this
}
public function fetchBars($string)
{
$folder = opendir($string);
while (false !== ($bar = readdir($folder)))
{
$this->bars[] = $bar;
}
closedir($folder);
}
}
// this function is outside class. so can be used without $this.
function myfunction()
{
echo "foo";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.