PHP快速建立一個對象的方法

來源:互聯網
上載者:User

前言

PHP 中的數組(尤其關聯陣列)是經常使用的 —— 因為方便。在一些架構中也經常見到返回數組格式的配置參數。然而有些時候可能需要對象而非數群組類型的配置參數,在查閱網路資料後找到了方法,作以記錄。

1. 強制轉換


$arr = [    'appid' => '101434352',    'appkey' => '09b8b372150171fbede71d782d46199a',    'callback' => 'http://test.nbycc.com/callback.php',    'scope' => 'add_t,add_pic_t,del_t',    'errorReport' => true,    'storageType' => 'file',    'host' => 'localhost',    'user' => 'root',    'password' => 'root',    'database' => 'test'];$obj = (Object)($arr);

2. stdClass類

stdClass 是 PHP 的一個基類,幾乎所有的類都繼承了這個類,所以任何時候都可以被 new,讓這個變數成為一個 Object。同時,執行個體化之後的 stdClass 是沒有任何屬性和方法的,也就是一個Null 物件。


$obj = new stdClass;$obj->appid = '101434352';$obj->appkey = '09b8b372150171fbede71d782d46199a';$obj->callback = 'http://test.nbycc.com/callback.php';$obj->scope = 'add_t,add_pic_t,del_t';$obj->errorReport = true;$obj->storageType = 'file';$obj->host = 'localhost';$obj->user = 'root';$obj->password = '';$obj->database = 'test';

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.