【发布时间】:2017-01-20 11:23:13
【问题描述】:
我是 OOP 的新手。我创建了这段代码,我知道如何用这种方式调用它
$john = new people('Bla', 'bla');
并使用$john->boy(); 调用它
但我想直接调用函数并在其上传递特定的(对于男孩.. $name, $beard 对于女孩... $name, $hair, $eyes)变量。
<?php
class people {
public $name;
protected $hair;
protected $eyes;
protected $beard;
public function __constructor($name, $hair, $eyes, $beard) {
$this->name = $name;
$this->hair = $hair;
$this->eyes = $eyes;
$this->beard = $beard;
}
public function getName() {
return $this->name;
}
public function getHair() {
return $this->hair;
}
public function getEyes() {
return $this-eyes;
}
public function getBeard() {
return $this->beard;
}
public static function boy() {
$name = getName();
$beard = getBeard();
echo $name . ' has ' . $beard . ' beard';
}
public static function girl() {
$name = getName();
$hair = getHair();
$eyes = getEyes();
echo $name . ' has ' . $hair . ' hair and ' . $eyes . ' eyes';
}
}
并直接用函数名调用&输出:
people::boy('John', 'long');
people::boy('Steve', 'small');
people::girl( 'Eva', 'long', 'blue' );
【问题讨论】:
-
不能从静态上下文调用非静态方法(使用this->...类必须通过new实例化)
-
你想要的不需要课程。您只需要一个带参数的函数。例如。
function boy($name, $beard) { // code } -
__constructorbtw 在 OOP 中无效。 RTM php.net/manual/en/language.oop5.decon.php - 老实说,我不知道你从哪里得到的,但我很想知道。 -
作为 OOP 的新手,我正在学习一些教程,只是更改了一些名称并替换了一些功能 XD