2

我只是不明白为什么我不能调用这样的对象。

<?php

$obj = (object) array (
        "happy" => " :) ",
        "sad" => " :( "
);

class MyClass
{
    function __construct () {}

    function something ()
    {
        echo "Hello World\n";
        echo $obj->sad;
    }
}

$class = new MyClass();
echo $obj->happy;
$class->something();

输出看起来像

:) Hello World

这不是我所期望的。IE

:) Hello World :(

我怎样才能使这项工作?

编辑:这就是我将实现这个例子的内容。将对象从全局范围传递到模型

4

4 回答 4

4

$obj未在函数范围内定义something。您可以通过global $obj在函数内部添加来使其全球化,但最好将其作为参数传递给函数。

编辑:

<?php
$obj = (object) Array(
    "happy" => " :) ",
    "sad" => " :( "
);
class MyClass {
  function something($obj) {
    echo "Hello World\n".$obj->sad;
  }
}
$class = new MyClass();
echo $obk->happy;
$class->something($obj);
于 2012-12-28T18:54:46.550 回答
2
<?php

$obj = (object) array (
        "happy" => " :) ",
        "sad" => " :( "
);

class MyClass
{
    function __construct (){
    }

    function something ()
    {
        global $obj;
        echo "Hello World\n";
        echo $obj->sad;
    }
}

$class = new MyClass();
echo $obj->happy;
$class->something();

?>

这将是一种方法。obj 不在此处的范围内,您必须将其设为全局或传递它。

将它传递给构造函数并保存实例..as here

<?php

$obj = (object) array (
        "happy" => " :) ",
        "sad" => " :( "
);

class MyClass
{   private $obj;
    function __construct ($obj) {
     $this->obj=$obj;

    }

    function something ()
    {
        echo "Hello World\n";
        echo $this->obj->sad;
    }
}

$class = new MyClass($obj);
echo $obj->happy;
$class->something();

但是您必须从所有函数中以 $this->obj 的形式访问 $obj

于 2012-12-28T19:03:14.363 回答
1

将 obj 作为参数传递给构造函数或方法本身,这是使用该方法的示例:

<?php

$obj = (object) array (
        "happy" => " :) ",
        "sad" => " :( "
);

class MyClass
{
    function __construct () {}

    function something ($obj)
    {
        echo "Hello World\n";
        echo $obj->sad;
    }
}

$class = new MyClass();
echo $obj->happy;
$class->something($obj);
于 2012-12-28T19:02:20.797 回答
0

这是因为在您的情况下$obj是在全局范围内,并且在您的班级范围内不可用。

打开您的错误报告,这将立即通过“尝试获取非对象的属性”类型的错误变得明显。

于 2012-12-28T18:56:58.613 回答