为什么不能在另一个对象中加载一个对象? [英] why cannot load an object inside another?

查看:45
本文介绍了为什么不能在另一个对象中加载一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是不明白为什么我不能像这样调用一个对象.

I just don't understand why i can't call an object like this.

<?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 :(

我怎样才能做到这一点??

how can I make this work??

这就是我将要实现的这个例子.将对象从全局作用域传递到模型

This is in what I will implement this example. passing objects from the global scope to a model

推荐答案

<?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 不在此范围内,您必须将其设为全局或传递.

That will be a way of doing it. obj is not in scope here, you have to either make it global, or pass it.

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

Pass it to constructor and save instance..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

But you will have to access $obj as $this->obj from all functions

这篇关于为什么不能在另一个对象中加载一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆