在子php oop中导入父函数数据

时间:2016-11-12 16:07:06

标签: php oop

我试图通过调用child中的父函数数据来学习php oop的简单方法。 但是我错了。

class name{
    var $firstname;
    var $lastname;
    var $name;
    public function name($firstname, $lastname){
        $this->firstname=$firstname;
        $this->lastname=$lastname;
        $this->name=$this->firstname." ".$this->lastname;
        return $this->name;
    }
}
class sentence extends name{
    var $name;
    var $letter;
    function sentence(){
        $this->letter="My name is ";
        echo $this->letter.$this->name;
    }
}
$name=new name(ABC, Xyz);
$letter=new sentence();

我创建了一个调用来获取名称输入,另一个子类来编写这个句子。但是无法在孩子中调用该名称。

3 个答案:

答案 0 :(得分:0)

快速解决,因为那可能是你想要的。

<?php
class name {

private $firstname;
private $lastname;
private $name;
private $sentence;

public function __construct($firstname, $lastname){
    $this->firstname = $firstname;
    $this->lastname = $lastname;
    $this->name = $firstname . " " . $lastname;
    $this->sentence = "My name is : " . $this->name;

}

public function getName(){
    return $this->name;
}

public function getSentence(){
    return $this->sentence;
 }
}

$instance = new name("test","lastname");

echo $instance->getSentence();
?>

答案 1 :(得分:0)

class name
{
    public $firstname;
    public $lastname;
    public $name;
    public function name($firstname, $lastname)
    {
        $this->firstname = $firstname;
        $this->lastname = $lastname;
        $this->name = $this->firstname.' '.$this->lastname;

        return $this->name;
    }
}
class sentence extends name
{
    public $name;
    public $letter;
    public function greeting()
    {
        $this->letter = 'My name is ';
        echo $this->letter.$this->name;
    }
}
//$name=new name(ABC, Xyz);
$letter = new sentence('ABC', 'Xyz');
$letter->greeting();

感谢@ManhNguyen

答案 2 :(得分:-1)

您是否尝试读取父类中的变量状态?

这不是OOP的工作原理。

您必须将所有变量组合在一起,或者将其作为参数传递给您想要访问数据的函数。

其次,您似乎没有使用__construct函数,而是将变量传递给new name()函数,该函数也是NO-NO。