PHP SplObjectStorage attach()函数介绍用法实例

2021年3月15日09:27:42 发表评论 711 次浏览

SplObjectStorage :: attach()function是PHP中的内置函数, 用于将对象添加到SplObjectStorage

语法如下:

void SplObjectStorage::attach($obj, $val)

参数:该函数接受上面提到的和下面描述的两个参数。

  • $ obj:这是必需的参数, 用于指定存储类的对象。
  • $ val:这是一个可选参数, 用于指定要添加的值。

返回值:该函数不返回任何值。

下面的程序说明了SplObjectStorage :: attach()PHP中的功能:

程序1:

<?php
  
// Declare new object
$obj = new StdClass;
  
// Create an empty storage class
$str = new SplObjectStorage();
  
// Attach $obj with String "lsbin"
$str ->attach( $obj , "lsbin" );
  
// Print Result 
var_dump( $str [ $obj ]);
  
?>

输出如下:

string(13) "lsbin"

程式2:

<?php
  
// Creating std classes
$obj1 = new StdClass;
$obj2 = new StdClass;
$obj3 = new StdClass;
$obj4 = new StdClass;
  
$str = new SplObjectStorage();
$str ->attach( $obj1 );
$str ->attach( $obj2 , "GFG" );
  
// Another way to use attach() function
$str [ $obj3 ] = "lsbin" ;
$str [ $obj4 ] = NULL ;
  
// Print Result
var_dump( $str [ $obj1 ]);
var_dump( $str [ $obj2 ]);
var_dump( $str [ $obj3 ]);
var_dump( $str [ $obj4 ]);
  
?>

输出如下:

NULL
string(3) "GFG"
string(13) "lsbin"
NULL

参考: https://www.php.net/manual/en/splobjectstorage.attach.php


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: