【问题标题】:How to make an object resident to a function call?如何使对象驻留在函数调用中?
【发布时间】:2013-07-09 22:42:15
【问题描述】:

我正在编写一个执行 SOAP 请求的 PHP 程序,它返回一个对象。我需要编写一个函数,从该对象中获取数据并以各种方式使用它,但如果对该对象中数据的 SOAP 请求已经驻留,我不希望它每次都执行 SOAP 请求。

伪代码示例:

$price = GetPartPrice("1234");


function GetPartPrice($part_number) {

If Parts_List_Object not found then do SOAP request to get Parts_List_Object. 

}

我看到的问题是,如果 Parts_List_Object 已经存在,我不知道在哪里或如何存储。我是否需要设置一些东西来使从 SOAP/JSON 请求中请求的 StdClass 对象成为全局对象,或者是否有更好的方法来完成这一切?谢谢!

【问题讨论】:

    标签: php object stdclass


    【解决方案1】:

    一种方法是为这些对象构建一个注册表,在其中存储您获取的对象并查找您需要的对象。这使您可以简单地获取对已加载实例的引用。一个非常基本的例子:

    class PartListRegistry {
        private static $list = array();
    
        // After you do the SOAP request, call this to save a reference to the object
        public static function addPartObject($key, $obj) {
            self::$list[$key] = $obj;
        }
    
        // Call this to see if the object exists already
        public static function getPartObject($key) {
            if (isset(self::$list[$key])) {
                return self::$list[$key];
            }
            return null;
        }
    }
    
    function GetPartPrice($part_number) {
        $part = PartListRegistry::getPartObject($part_number);
        if ($part === null) {
            $part = .... // Do your SOAP request here
            // Save a reference to the object when you're done
            PartListregistry::addPartObject($part_num, $part);
        }
        // Do your stuff with the part ....
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多