0

嗨,请看一下下面的代码。

<?php
class A
{
    public $name;

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

class B extends A
{
    public function setName()
    {
        $this->name = 'Prasad';
    }
}

$obj = new B();

echo $obj->getName();

?>

在这里,当我回显名称时,它什么也不显示。与 A 类中的 $name 相关。这个问题是 getName 还是 setName 的问题?如何从扩展类 B 中设置类 A 中的 $name 变量。如何从类 B 对象中获取它。感谢我错过的任何提示或解释。

4

5 回答 5

1

您之前没有设置名称(使用$obj->setName())。

于 2012-07-16T01:53:38.533 回答
1

setName()你的代码大部分都在那里,事实上,如果你添加一行告诉代码调用函数,你会有一个工作示例:

$obj = new B();
$obj->setName();
echo $obj->getName();

More typically you would use a set function with a parameter, then pass the value you want to set. You would also set the $name property to protected, which means the value must be accessed via the set & get methods (more on visibility in the manual):

<?php
class A
{
    protected $name;

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

class B extends A
{
    public function setName($name)
    {
        $this->name = $name;
    }
}

$obj = new B();
$obj->setName('Prasad');
echo $obj->getName();

?>
于 2012-07-16T01:55:54.693 回答
1

Technically, it's echoing the $name variable (which is undefined at that point). Unfortunately, it hasn't been set yet. Try using $obj->setName() to set the name.

于 2012-07-16T01:57:28.750 回答
1

Yes, as SomeKittens suggested you need to call setName() first.

class A
{
    public $name;

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

class B extends A
{
    public function setName()
    {
        $this->name = 'Prasad';
    }
}

$obj = new B();
$obj->setName();
echo $obj->getName();

However, it might be better to perform the setting of the name in the constructor of B, as:

class A
{
    public $name;

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

class B extends A
{
    public function B()
    {
        $this->name = 'Prasad';
    }
}

$obj = new B();

echo $obj->getName();

This printed Prasad for me using http://writecodeonline.com/php/ to test the code.

Even better, pass the name 'Prasad' when creating the new B object, as:

class A
{
    public $name;

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

class B extends A
{
    public function B( $value = 'Prasad' )
    { 
        $this->name = $value;
    }
}

$obj = new B();

echo $obj->getName(), "<br>";

$obj = new B( 'John' );

echo $obj->getName();
于 2012-07-16T01:58:21.577 回答
0

这是因为您没有先设置 name 属性。呼叫B->setName(),然后您可以通过呼叫获得名称B->getName()

于 2012-07-16T01:54:03.333 回答