函数在面向对象的php结构中没有返回值

时间:2014-07-30 10:19:22

标签: php function oop inheritance

我是面向对象PHP的新手,我正在学习一些基本的例子。我有index.php文件,其中我创建了类并使用了getter和setter。在class_lib.php文件中,我创建了类的对象并尝试回显该值。但我没有得到任何价值。

inde.php

<?php
class person {
var $name;

 function __construct($persons_name) 
 {
        $this->name = $persons_name;
 }

 function set_name($new_name) 
 {
        $this->name = $new_name;
 }

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

class employee extends person
{
    function __construct($employee_name)
    {
        $this->set_name($employee_name);
    }
}
?>

class_lib.php

<?php
include "index.php";

$stefan = new person("Stefan Mischook");
echo "Stefan's full name: " . $stefan->get_name();
echo '<br>';
$james = new employee("Johnny Fingers");
echo "new employee---> " . $james->get_name();
?>

2 个答案:

答案 0 :(得分:0)

以下是在PHP 5.4.4上执行的代码:http://ideone.com/KvrQVF

输出:

Stefan's full name: Stefan Mischook
new employee---> Johnny Fingers

似乎工作正常。

答案 1 :(得分:0)

将class_lib.php代码更改为index.php代码并将index.php代码更改为class_lib.php

的index.php

<?php
    include "class_lib.php";
    $stefan = new person("Stefan Mischook");
    echo "Stefan's full name: " . $stefan->get_name();
    echo '<br>';
    $james = new employee("Johnny Fingers");
    echo "new employee---> " . $james->get_name();
?>

class_lib.php

<?php
    class person {
    var $name;
    function __construct($persons_name) 
    {
        $this->name = $persons_name;
    }
    function set_name($new_name) 
    {
        $this->name = $new_name;
    }
    function get_name()
    {
        return $this->name;
    }
    }
    class employee extends person
    {
    function __construct($employee_name)
    {
        $this->set_name($employee_name);
    }
    }
 ?>