我是 OOP 的新手。我创建了这段代码,我知道如何用这种方式调用它
$john = new people('Bla', 'bla');
并使用$john->boy();
调用它
但我想直接调用函数并传递特定的(对于boy ... $name, $beard
for girl ... $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';
}
}
并致电&amp;直接输出函数名称:
people::boy('John', 'long');
people::boy('Steve', 'small');
people::girl( 'Eva', 'long', 'blue' );
答案 0 :(得分:1)
与ka_lin sad一样,你不能从静态上下文中调用非静态方法;那么,你能为代码工作的是:
<?php
class people {
protected $name;
protected $hair;
protected $eyes;
protected $beard;
public function __construct($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, $beard) {
$boy = new self($name, null, null, $beard);
$name = $boy->getName();
$beard = $boy->getBeard();
echo $name . ' has ' . $beard . ' beard' . PHP_EOL;
}
public static function girl($name, $hair, $eyes) {
$girl = new self($name, $hair, $eyes, null);
$name = $girl->getName();
$hair = $girl->getHair();
$eyes = $girl->getEyes();
echo $name . ' has ' . $hair . ' hair and ' . $eyes . ' eyes' . PHP_EOL;
}
}
people::boy('John', 'long');
people::boy('Steve', 'small');
people::girl( 'Eva', 'long', 'blue' );