日期:2014-05-17  浏览次数:20394 次

PHP对象编程问题,Call to a member function hello() on a non-object
<?php

$instest = new test();
$insobject = new object();
$insobject->objectValue = "final";
$instest->test();

class test{
var $testValue = "testValueins";
function test(){
print_r($insobject);
$insobject->hello();
}
}

class object{
var $objectValue = "original";
function hello(){
echo $objectValue;
}
}

?>


报错如下

Notice: Undefined variable: insobject in C:\wamp\www\zhebo\test.php on line 11
Call Stack
Notice: Undefined variable: insobject in C:\wamp\www\zhebo\test.php on line 12
Fatal error: Call to a member function hello() on a non-object in C:\wamp\www\zhebo\test.php on line 12

这有什么问题么,怎样才可以达到在实例里引用别的实例里的方法,或者有什么更好地解决方法?
我很急,希望大家可以帮忙。非常感谢啊。非常紧急。第一次用对象的思想编程还不太懂啊。

------解决方案--------------------
未经传递或全局声明,内部不能访问外部的变量(对象也是用变量做载体的)
这是 php 语法的基本规则,不可逾越

$insobject = new object();
$insobject->objectValue = "final";

$instest = new test($insobject);

//$instest->test(); 这是构造函数,一般不这样调用
 
class test{
  var $testValue = "testValueins";
  function test($insobject){
    print_r($insobject);
    $insobject->hello();
  }
}
 
class object{
  var $objectValue = "original";
  function hello(){
    echo $this->objectValue; //访问属性要这样
  }
}
object Object ( [objectValue] => final ) final
------解决方案--------------------
调用构造函数和 new 是一样的
都是返回一个类的实例