我只是不明白为什么我不能这样称呼这个对象。
<?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
并不是我所期待的。即。
:) Hello World :(
我怎样才能做到这一点?
编辑: 这就是我将要实现的示例。 passing objects from the global scope to a model
答案 0 :(得分: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);
答案 1 :(得分: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不在此范围内,您必须使其成为全局或传递它。
将它传递给构造函数并保存实例..这里
<?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();
但是您必须从所有函数
访问$ obj作为$ this-&gt; obj答案 2 :(得分: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);
答案 3 :(得分:0)
这是因为在您的情况下$obj
处于全局范围内,并且不适用于您的班级范围。
打开错误报告,这会立即变得明显,“尝试获取非对象属性”类型的错误。