请帮助我找出如何在PHP类中定义构造函数。
我以这种方式写了一堂课:class ABC
{
private $x=5;
function display()
{
echo $this->x;
}
}
现在我正在尝试为类定义一个参数化构造函数,因此我可以创建具有适当值的对象$ x。我怎么能这样做?
答案 0 :(得分:3)
class ABC
{
private $x;
function __construct($x)
{
$this->x = $x;
}
function display()
{
echo $this->x;
}
}
答案 1 :(得分:3)
虽然其他两个人已经正确回答了(抱歉懒得说出你的名字:P),但必须说你也可以这样写你的构造函数:
<?php
// Constructor
class Object {
function Object($vars) {
}
}
?>
构造函数也可以与类本身同名,并不总是__construct()
从official documentation更新
警告强> 旧样式构造函数在PHP 7.0中已弃用,将在以后的版本中删除。你应该总是在新代码中使用__construct()。
答案 2 :(得分:2)
查看此文档链接:http://us.php.net/manual/en/language.oop5.decon.php
<?php
/**
* a class demonstrating constructors
*
*/
class ABC
{
var $x;
public function __construct($arg)
{
// this function gets its arguments via the class constructor
$this->x = $arg;
}
public function showVariable()
{
echo $this->x;
}
}
?>
<?php
// see the class constructor can take an argument (to be passed to the __construct) function
// it can be an array or just a variable
$abc = new ABC("Hello World");
$abc->showVariable();
?>