<?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也打印不出类来 不知道为什么 求高手解答
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也打印不出类来 不知道为什么 求高手解答
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过去值 是不能直接调用类的私有属性的
另外,你的__toString魔术方法,你看看手册要有返回值的,你都没返回值,当执行到echo $example;这一步的时候$example还是个对象,echo怎么能打印对像呢?所以会报错。
应该$this->a = $b;