PHP getter方法问题

时间:2011-07-20 02:34:03

标签: php methods getter

我是PHP新手,请原谅这个问题的基本性质。

我有一个类:“CustomerInfo.php”,我将其包含在另一个类中。然后我尝试使用定义的setter方法设置CustomerInfo对象的变量,并尝试使用getter方法回显该变量。问题是吸气剂不起作用。但是,如果我直接访问变量,我可以回显该值。我很困惑......

    <?php
class CustomerInfo
{

    public $cust_AptNum;



    public function _construct()
    {
        echo"Creating new CustomerInfo instance<br/>";
        $this->cust_AptNum = "";

    }

    public function setAptNum($apt_num)
    {
        $this->cust_AptNum = $apt_num;
    }

    public function getAptNum()
    {
        return $this->cust_AptNum;
    }


}
?>

<?php

include ('CustomerInfo.php');
$CustomerInfoObj = new CustomerInfo();

$CustomerInfoObj->setAptNum("22");
//The line below doesn't output anything
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
//This line outputs the value that was set
echo "CustomerAptNo = $CustomerInfoObj->cust_AptNum<br/>";
?>

2 个答案:

答案 0 :(得分:5)

尝试

echo 'CustomerAptNo = ' . $CustomerInfoObj->getAptNum() . '<br/>';

或者您需要将方法调用放在“复杂(卷曲)语法”

echo "CustomerAptNo = {$CustomerInfoObj->getAptNum()} <br/>";

当你调用方法时,不是带双引号的变量。

答案 1 :(得分:1)

对于concat字符串和变量,您可以使用sprintf方法来提高应用程序的性能

而不是:

echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";

这样做:

echo sprintf("CustomerAptNo = %s <br />", $CustomerInfoObj->getAptNum()); 

检查http://php.net/sprintf了解详情