<?php
class A{
var $a;
function A($b){
echo "A has been constructed";
$a=$b;
}
public function _toString(){
echo "A has an attribute $a";
}
}
$b='string';
$example=new A($b);
echo $example->a;
echo $example;
?>运行结果:
A has been constructed
Catchable fatal error: Object of class A could not be converted to string in D:\programming\PHP\Class\1.php on line 15example->a也打印不出来,_toString也打印不出类来  不知道为什么  求高手解答

解决方案 »

  1.   


    class A{
    var $a;
    function A($b){
    echo "A has been constructed";
    $a=$b;
    }
    public function _toString(){
    echo "A has an attribute $a";
    }
    public function seta($a){
        $this->a  = $a;
    }
    public function geta(){
    return $this->a;
    }
    }
    $b='string';
    $example=new A($b);
    $example->seta($b);
    echo $example->geta();
            首先要访问类私有属性是要通脱 setxx  设置值   用getxx过去值   是不能直接调用类的私有属性的 
      

  2.   

    是__toString而不是_tostring,还有函数里面是return 一个值
      

  3.   

    这里面根本就没有私有变量,都是公有的,在构造函数里面你直接可以写上 $this->a = $b;
    另外,你的__toString魔术方法,你看看手册要有返回值的,你都没返回值,当执行到echo $example;这一步的时候$example还是个对象,echo怎么能打印对像呢?所以会报错。
      

  4.   

    构造函数给变量赋值,
    应该$this->a = $b;