简体   繁体   English

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

[英]Importing Parent function data in child php oop

I am trying to learn simple method of php oop by calling parent function data in child. 我试图通过在子级中调用父函数数据来学习php oop的简单方法。 However somewhere I am making mistake. 但是我在某个地方犯了错误。

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();

I have created one calls to get name input and another child class to write the sentence. 我创建了一个调用来获取名称输入,并创建了另一个子类来编写句子。 However not able to call the name in child. 但是不能在孩子中叫名字。

a quick fix since thats probably what you want. 快速修复,因为那可能就是您想要的。

<?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();
?>
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();

Thanks to @ManhNguyen 感谢@ManhNguyen

Are you trying to read the state of variables in a parent class? 您是否要读取父类中变量的状态?

That is not how OOP works. 这不是OOP的工作方式。

You have to either group together all the variables into one class or pass it trough as an argument to the function you want to have access to the data. 您必须将所有变量组合到一个类中,或者将其作为参数传递给想要访问数据的函数。

Second of all you don't seem to not be using a __construct function and yet pass variables into the new name() function that is also a NO-NO. 第二,您似乎并没有使用__construct函数,而是将变量传递到也是NO-NO的new name()函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM