到目前為止,最簡單且正確的方法是實例化一個空的通用 PHP 物件,然後您可以根據自己的目的修改它
<?php $genericObject = new stdClass(); ?>
我費了好大勁才找到這個,希望它能幫助到其他人!
要建立新的物件,請使用 new
陳述式來實例化類別
<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();
?>
完整說明請參閱類別與物件章節。
如果一個物件被轉換為物件,它不會被修改。如果任何其他類型的值被轉換為物件,則會建立內建類別 stdClass 的新實例。如果該值為 null
,則新實例將為空。 陣列會轉換為一個物件,其屬性名稱為鍵名,值為對應的值。請注意,在 PHP 7.2.0 之前,數字鍵是無法直接存取的,除非透過迭代。
<?php
$obj = (object) array('1' => 'foo');
var_dump(isset($obj->{'1'})); // 從 PHP 7.2.0 開始輸出 'bool(true)';之前為 'bool(false)'
var_dump(key($obj)); // 從 PHP 7.2.0 開始輸出 'string(1) "1"';之前為 'int(1)'
?>
對於任何其他值,名為 scalar
的成員變數將包含該值。
<?php
$obj = (object) 'ciao';
echo $obj->scalar; // 輸出 'ciao'
?>
到目前為止,最簡單且正確的方法是實例化一個空的通用 PHP 物件,然後您可以根據自己的目的修改它
<?php $genericObject = new stdClass(); ?>
我費了好大勁才找到這個,希望它能幫助到其他人!
在 PHP 7 中,有幾種方法可以建立空物件
<?php
$obj1 = new \stdClass; // 實例化 stdClass 物件
$obj2 = new class{}; // 實例化匿名類別
$obj3 = (object)[]; // 將空陣列轉換為物件
var_dump($obj1); // object(stdClass)#1 (0) {}
var_dump($obj2); // object(class@anonymous)#2 (0) {}
var_dump($obj3); // object(stdClass)#3 (0) {}
?>
$obj1 和 $obj3 的類型相同,但 $obj1 !== $obj3。此外,使用 json_encode() 後,三者都會變成簡單的 JS 物件 {}
<?php
echo json_encode([
new \stdClass,
new class{},
(object)[],
]);
?>
輸出:[{},{},{}]
從 PHP 5.4 開始,我們可以使用更簡潔的語法建立帶有屬性和值的 stdClass 物件:
<?php
$object = (object) [
'propertyOne' => 'foo',
'propertyTwo' => 42,
];
?>
這是「stdObject」類別的新版本。在 MVC 設計模式中擴展控制器時非常有用,使用者可以建立自己的類別。
希望對您有所幫助。
<?php
class stdObject {
public function __construct(array $arguments = array()) {
if (!empty($arguments)) {
foreach ($arguments as $property => $argument) {
$this->{$property} = $argument;
}
}
}
public function __call($method, $arguments) {
$arguments = array_merge(array("stdObject" => $this), $arguments); // Note: method argument 0 will always referred to the main class ($this).
if (isset($this->{$method}) && is_callable($this->{$method})) {
return call_user_func_array($this->{$method}, $arguments);
} else {
throw new Exception("Fatal error: Call to undefined method stdObject::{$method}()");
}
}
}
// Usage.
$obj = new stdObject();
$obj->name = "Nick";
$obj->surname = "Doe";
$obj->age = 20;
$obj->adresse = null;
$obj->getInfo = function($stdObject) { // $stdObject referred to this object (stdObject).
echo $stdObject->name . " " . $stdObject->surname . " have " . $stdObject->age . " yrs old. And live in " . $stdObject->adresse;
};
$func = "setAge";
$obj->{$func} = function($stdObject, $age) { // $age is the first parameter passed when calling this method.
$stdObject->age = $age;
};
$obj->setAge(24); // Parameter value 24 is passing to the $age argument in method 'setAge()'.
// Create dynamic method. Here i'm generating getter and setter dynimically
// Beware: Method name are case sensitive.
foreach ($obj as $func_name => $value) {
if (!$value instanceOf Closure) {
$obj->{"set" . ucfirst($func_name)} = function($stdObject, $value) use ($func_name) { // Note: you can also use keyword 'use' to bind parent variables.
$stdObject->{$func_name} = $value;
};
$obj->{"get" . ucfirst($func_name)} = function($stdObject) use ($func_name) { // Note: you can also use keyword 'use' to bind parent variables.
return $stdObject->{$func_name};
};
}
}
$obj->setName("John");
$obj->setAdresse("Boston");
$obj->getInfo();
?>
<!--範例展示如何將陣列轉換為 stdClass 物件以及如何存取其值以進行顯示-->
<?php
$num = array("Garha","sitamarhi","canada","patna"); //建立一個陣列
$obj = (object)$num; //將陣列轉換為 stdClass 物件
echo "<pre>";
print_r($obj); //透過陣列轉換建立的 stdClass 物件
$newobj = new stdClass();//建立一個新的 stdClass 物件
$newobj->name = "India";
$newobj->work = "Development";
$newobj->address="patna";
$new = (array)$newobj;//將 stdClass 轉換為陣列
echo "<pre>";
print_r($new); //印出新的物件
##如何處理關聯式陣列
$test = [Details=>['name','roll number','college','mobile'],values=>['Naman Kumar','100790310868','Pune college','9988707202']];
$val = json_decode(json_encode($test),false);//將陣列轉換為 stdClass 物件
echo "<pre>";
print_r($val);
echo ((is_array($val) == true ? 1 : 0 ) == 1 ? "array" : "not an array" )."</br>"; // 檢查是否為陣列
echo ((is_object($val) == true ? 1 : 0 ) == 1 ? "object" : "not an object" );//檢查是否為物件
?>
還記得一些 JavaScript 的實作方式嗎?
// var timestamp = (new Date).getTime();
現在用 PHP 5.4.* 就可以做到;
<?php
類別 Foo
{
公開 $a = "我是 a!";
公開 $b = "我是 b!";
公開 $c;
公開 函式 getB() {
返回 $this->b;
}
公開 函式 setC($c) {
$this->c = $c;
返回 $this;
}
公開 函式 getC() {
返回 $this->c;
}
}
印出 (新 Foo)->a; // 我是 a!
印出 (新 Foo)->getB(); // 我是 b!
?>
或者
<?php
// $_GET["c"] = "我是 c!";
印出 (新 Foo)
->setC($_GET["c"])
->getC(); // 我是 c!
?>
您可以使用以下方式建立[遞迴]物件
<?php
$literalObjectDeclared = (物件) 陣列(
'foo' => (物件) 陣列(
'bar' => 'baz',
'pax' => 'vax'
),
'moo' => 'ui'
);
印出 $literalObjectDeclared->foo->bar; // 輸出 "baz"!
?>