Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
PHP: Standard PHP Library (SPL) 関数 - Manual
[go: Go Back, main page]

PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

ArrayIterator::current" width="11" height="7"/> <socket_write
Last updated: Thu, 31 May 2007

view this page in

CLV. Standard PHP Library (SPL) 関数

導入

SPLは、標準的な問題を解決するためのインターフェイスやクラスを集めたものです。

ティップ

SPL のより詳細なドキュメントは » こちら にあります。

インストール手順

このエクステンションは、PHP 5 ではデフォルトでコンパイルされ利用可能です。

定義済み定数

以下の定数が定義されています。 この関数の拡張モジュールが PHP 組み込みでコンパイルされているか、 実行時に動的にロードされている場合のみ使用可能です。

警告

PHP 5.1 以降、SPL はクラス定数を使用します。それより前のリリースでは、 RIT_LEAVES_ONLY のような形式のグローバル定数を使用します。

RecursiveIteratorIterator::LEAVES_ONLY (integer)
RecursiveIteratorIterator::SELF_FIRST (integer)
RecursiveIteratorIterator::CHILD_FIRST (integer)
CachingIterator::CALL_TOSTRING (integer)
CachingIterator::CATCH_GET_CHILD (integer)

目次

ArrayIterator::current — 現在の配列エントリを返す
ArrayIterator::key — 現在の配列キーを返す
ArrayIterator::next — 次のエントリに移動する
ArrayIterator::rewind — 配列を最初に巻き戻す
ArrayIterator::seek — 位置を検索します
ArrayIterator::valid — 配列がまだエントリを持っているかどうかチェックする
ArrayObject::append — 値を追加する
ArrayObject::__construct — 新規配列オブジェクトを生成する
ArrayObject::count — イテレータにある要素の数を返す
ArrayObject::getIterator — ArrayObject インスタンスから新規イテレータを生成する
ArrayObject::offsetExists — 要求された $index が存在するかどうかを返す
ArrayObject::offsetGet — 指定した $index の値を返す
ArrayObject::offsetSet — 指定した $index に $newval をセットする
ArrayObject::offsetUnset — 指定した $index の値を解除する
CachingIterator::hasNext — 内部イテレータが有効な次の要素を持つかどうかをチェックする
CachingIterator::next — イテレータを前方に移動する
CachingIterator::rewind — イテレータを巻き戻す
CachingIterator::__toString — 現在の要素の文字列表現を返す
CachingIterator::valid — 現在の要素が有効かどうかをチェックする
CachingRecursiveIterator::getChildren — 内部イテレータの子を CachingRecursiveIterator として返す
CachingRecursiveIterator::hasChildren — 内部イテレータの現在の要素が子を持つかどうかチェックする
DirectoryIterator::__construct — パスから新規ディレクトリイテレータを生成する
DirectoryIterator::current — これ自身を返す (Iterator インターフェースが必要)
DirectoryIterator::getATime — ファイルの最終アクセス時刻を取得する
DirectoryIterator::getCTime — ファイルの inode 修正時刻を取得する
DirectoryIterator::getChildren — もしディレクトリであれば現在のエントリのイテレータを返す
DirectoryIterator::getFilename — 現在のディレクトリエントリのファイル名を返す
DirectoryIterator::getGroup — ファイルのグループを取得する
DirectoryIterator::getInode — ファイルの inode を取得する
DirectoryIterator::getMTime — ファイルの最終修正時刻を取得する
DirectoryIterator::getOwner — ファイルの所有者を取得する
DirectoryIterator::getPath — ディレクトリパスを返す
DirectoryIterator::getPathname — 現在のディレクトリエントリのパスとファイル名を返す
DirectoryIterator::getPerms — ファイルのパーミッションを取得する
DirectoryIterator::getSize — ファイルサイズを取得する
DirectoryIterator::getType — ファイルタイプを取得する
DirectoryIterator::isDir — ファイルがディレクトリであれば true を返す
DirectoryIterator::isDot — 現在のエントリが '.' もしくは '..' の場合 true を返す
DirectoryIterator::isExecutable — ファイルが実行可能な場合 true を返す
DirectoryIterator::isFile — ファイルが通常のファイルの場合 true を返す
DirectoryIterator::isLink — ファイルがシンボリックリンクの場合 true を返す
DirectoryIterator::isReadable — ファイルが読込可能であれば true を返す
DirectoryIterator::isWritable — ファイルが書き込み可能であれば true を返す
DirectoryIterator::key — 現在のディレクトリエントリを返す
DirectoryIterator::next — 次のエントリに移動する
DirectoryIterator::rewind — ディレクトリを最初に巻き戻す
DirectoryIterator::valid — ディレクトリがまだエントリを持っているかどうかチェックする
FilterIterator::current — 現在の要素の値を取得する
FilterIterator::getInnerIterator — 内部イテレータを取得する
FilterIterator::key — 現在のキーを取得する
FilterIterator::next — イテレータを前に移動する
FilterIterator::rewind — イテレータを巻き戻す
FilterIterator::valid — 現在の要素が有効かどうかをチェックする
LimitIterator::getPosition — 現在の位置を返す
LimitIterator::next — イテレータを前に移動する
LimitIterator::rewind — イテレータを指定したオフセットに巻き戻す
LimitIterator::seek — 与えられた位置を検索する
LimitIterator::valid — 現在の要素が有効かどうかをチェックする
ParentIterator::getChildren — ParentIterator に含まれる内部イテレータの子を返す
ParentIterator::hasChildren — 内部イテレータの現在の要素が子を持つかどうかをチェックする
ParentIterator::next — イテレータを前に移動する
ParentIterator::rewind — イテレータを巻き戻す
RecursiveDirectoryIterator::getChildren — ディレクトリであれば、現在のエントリに対するイテレータを返す
RecursiveDirectoryIterator::hasChildren — 現在のエントリがディレクトリかつ '.' もしくは '..' でないかどうかを返す
RecursiveDirectoryIterator::key — 現在のディレクトリエントリのパスとファイル名を返す
RecursiveDirectoryIterator::next — 次のエントリに移動する
RecursiveDirectoryIterator::rewind — ディレクトリを最初に巻き戻す
RecursiveIteratorIterator::current — 現在の要素の値にアクセスする
RecursiveIteratorIterator::getDepth — 再帰的なイテレーションにおける現在の深さを取得する
RecursiveIteratorIterator::getSubIterator — 現在の有効なサブイテレータを取得する
RecursiveIteratorIterator::key — 現在のキーにアクセスする
RecursiveIteratorIterator::next — 次の要素に移動する
RecursiveIteratorIterator::rewind — トップレベルの内部イテレータの先頭要素にイテレータを巻き戻す
RecursiveIteratorIterator::valid — 現在の位置が有効かどうかをチェックする
SimpleXMLIterator::current — 現在の SimpleXML エントリを返す
SimpleXMLIterator::getChildren — SimpleXML である場合、現在のエントリに対するイテレータを返す
SimpleXMLIterator::hasChildren — 現在のエントリが SimpleXML オブジェクトかどうかを返す
SimpleXMLIterator::key — 現在の SimpleXML のキーを返す
SimpleXMLIterator::next — 次のエントリに移動する
SimpleXMLIterator::rewind — SimpleXML を最初に巻き戻す
SimpleXMLIterator::valid — SimpleXML がまだエントリを持っているかどうかをチェックする
class_implements — 与えられたクラスが実装しているインターフェースを返す
class_parents — 与えられたクラスの親クラスを返す
iterator_count — イテレータにある要素をカウントする
iterator_to_array — イテレータを配列にコピーする
spl_autoload_call — 要求されたクラスを読み込むために、すべての登録済みの __autoload() 関数を試す
spl_autoload_extensions — spl_autoload 用のデフォルトの拡張子を登録し、それを返す
spl_autoload_functions — すべての登録済み __autoload() 関数を返す
spl_autoload_register — 指定した関数を __autoload() の実装として登録する
spl_autoload_unregister — 指定した関数の、__autoload() の実装としての登録を解除する
spl_autoload — __autoload() のデフォルト実装
spl_classes — 利用可能な SPL クラスを返す
spl_object_hash — 指定したオブジェクトのハッシュ ID を返す


add a note add a note User Contributed Notes
Standard PHP Library (SPL) 関数
semperluc (at) yahoo._forgot_the_rest
02-Feb-2007 06:43
<?php
/*
How to store SPL Iterator results (rather than just echo-and-forget):

The library of Iterators  are object based, so you need to trick the little rascals into an array. 
Here's how (two ways) ...

1. Explicit typecasts: $a[] = (array)$Obj->objMethod();

2. Array definition: $a[] = array( key => $Obj->objMethod() );

Examples: DirectoryIterator()
*/

// 1. explicity typecast object as array
foreach ( new DirectoryIterator('./') as $Item )
{
 
$fname = (array)$Item->getFilename();
 
$dir_listing[] = $fname[0];
}

//
echo "<pre>";
print_r($dir_listing); unset($dir_listing);
echo
"</pre><hr />";
//

// or

// 2. define array as key => object->method
foreach ( new DirectoryIterator('./') as $Item )
{
 
$dir_listing[] = array (
   
"fname" => $Item->getFilename(),       
   
"path" => $Item->getPathname(),
   
"size" => $Item->getSize(),                   
   
"mtime" => $Item->getMTime()
  );
}

//
echo "<pre>";
print_r($dir_listing); unset($dir_listing);
echo
"</pre>";
//
?>
kevin at oceania dot net
07-Mar-2006 05:21
The most comprehensive of all tutorials regarding SPL has been written with some help from Marcus and can be found here.
http://www.phpro.org/tutorials/Introduction-to-SPL.html

Enjoy
ville</.>witt</a>gmail</.>com
13-Jan-2006 05:37
These to funtions has excatly the same output, the only diff. is in which directory iterator they use. I hope someone out there can use it:
<?
function listfilesin1 ($dir = ".", $depth=0) {
    echo
"Dir: ".$dir."<br/>";
    foreach(new
DirectoryIterator($dir) as $file) {
        if (!
$file->isDot()) {
            if (
$file->isDir()) {
               
$newdir = $file->getPathname();
               
listfilesin1($newdir, $depth+1);
            } else {
                echo
"($depth)".$file->getPathname() . "<br/>";
            }
        }
    }
}
function
listfilesin2 ($dir = ".", $depth=0) {
    echo
"Dir: ".$dir."<br/>";
    foreach(new
RecursiveDirectoryIterator($dir) as $file) {
        if (
$file->hasChildren(false)) {
           
$newdir = $file->key();
           
listfilesin2($newdir, $depth+1);
        } else {
            echo
"($depth)".$file->key() . "<br/>";
        }
    }
}
listfilesin();
?>
jce at vt dot ilw dot agrl dot ethz dot ch
11-Nov-2005 04:51
You may access the ArrayObject as an array by using explicit typecasts:

class myArrayObject extends ArrayObject
{
    function getArray()
    {
        return (array) $this;
    }
}
adove at booyahnetworks dot com
11-Oct-2005 02:45
Something to note that, at least to me, seems pretty important and is not entirely clear in the documentation is the fact that the ArrayObject class supports get/set on uni-dimensional keys and get ONLY on *passed* multi-dimensional keys/paths (see source below). If you, like me, need to support array accesss overloading for multi-dimensional data, you will need to derive from ArrayObject and overide the ArrayAccess interface methods to "walk" passed data and convert embedded arrays to objects of some kind...

Reference Bug 34816 @ http://bugs.php.net/bug.php?id=34816.

Illustration of the issue:

$a = array(
    "test" => array(
        "one" => "dunno",
        "two" => array(
            "peekabo" => "do you see me?",
            "anyone" => array("there")
            )
        )
    );
$oArray = new ArrayObject($a);
var_dump($oArray);

$oArray["three"] = "No problems here.";

echo "\n\\test\\one == " . $oArray["test"]["one"] . "\n\n";

// NEITHER of the two below will work!
$oArray["test"]["one"] = "Yes I do!";
$oArray["test"]["yes"] = array(
    "hello" => "Goodbye!"
    );

var_dump($oArray);

---
Note from the extension author:
Actually there is RecursiveArrayObject and RecursiveArrayIterator to deal with recursive structures. However this does not always solve all multidimensional issues as expected.
helly at php dot net
25-Sep-2005 06:41
There is a RecursiveFilterIterator that makes the above code much easier. And then ther is ParentIterator thta is already a filtering recursive iterator that only accepts elements that have children, with a RecursiveDirectoryIterator as inner iterator you would obviously get only the directories. Further more it ensures that it creates the correct children. All in all you simply need to do this:

$it = new RecursiveDirectoryIterator($path);
$it = new ParentIterator($it);
$it = new RecursiveIteratorIteator($it);

foreach($it as $dir  => $o) { ... }
ericjr [!_ at _!] junioronline dot us
12-Jul-2005 08:57
In addition to "mastabog at hotmail dot com"`s note about the recursive directory iterator, his method skips symlinked directories, because getChildren() doesn't return true if the directory is symlinked.

To fix this, the script should always instanciate an innerInterator when dealing with symlinked directories like so:

<?
class DirectoriesOnlyIterator extends FilterIterator implements RecursiveIterator
{
  
public function __construct ($path)
   {
      
parent::__construct(new RecursiveDirectoryIterator($path));
   }

  
public function accept()
   {
       return
$this->getInnerIterator()->hasChildren();
   }

  
public function hasChildren ()
   {
       return
$this->hasChildren() || $this->isLink();
   }
  
  
public function getChildren ()
   {
       return new
self($this->getInnerIterator()->getPathname());
   }
}
just_somedood at yahoo dot com
28-Jun-2005 04:11
Just a follow up on dave at tunasoft's post.  To give his example of ArrayAccess use of foreach, it's easiest to implement IteratorAggregate and use the ArrayIterator object as the iterator, as below:

<?php

class Collection implements ArrayAccess,IteratorAggregate
{
   
public $objectArray = Array();
   
//**these are the required iterator functions   
   
function offsetExists($offset)
    {         
        if(isset(
$this->objectArray[$offset]))  return TRUE;
        else return
FALSE;         
    }   
   
    function &
offsetGet($offset)
    {  
        if (
$this->offsetExists($offset))  return $this->objectArray[$offset];
        else return (
false);
    }
   
    function
offsetSet($offset, $value)
    {         
        if (
$offset$this->objectArray[$offset] = $value;
        else 
$this->objectArray[] = $value;
    }
   
    function
offsetUnset($offset)
    {
        unset (
$this->objectArray[$offset]);
    }
   
    function &
getIterator()
    {
        return new
ArrayIterator($this->objectArray);
    }
   
//**end required iterator functions

   
public function doSomething()
    {
        echo
"I'm doing something";
    }
}

?>

I LOVE the new SPL stuff in PHP.  The above allows you to have methods inside of your array, and when treated as an array the data components are returned, such as:

<?php
class Contact
{
   
protected $name = NULL;

   
public function set_name($name)
    {
       
$this->name = $name;
    }
   
   
public function get_name()
    {
        return (
$this->name);
    }
}

$bob = new Collection();
$bob->doSomething();
$bob[] = new Contact();
$bob[5] = new Contact();
$bob[0]->set_name("Superman");
$bob[5]->set_name("a name of a guy");

foreach (
$bob as $aContact)
{
     echo
$aContact->get_name() . "\r\n";
}
?>

Would work just fine.  This make code so much simpler and easy to follow, it's great.  This is exactly the direction I had hoped PHP5 was going!
zaufi at sendmail dot ru
17-Apr-2005 11:24
I'v done with my PluginsManager... Sample code to use plugins may looks lije this:
<?php
require_once('lib/plugins-manager.inc.php');

// Load and use conctere plugin module
$p = new Plugin('test.class.php');
$test = $p->class_factory('test', 1, 2);
$test->foo();

// ... oneliner ;)
$p = $pm['test.class.php']->class_factory('test', 1, 2)->foo();

// Scan for plugable modules, construct an instance and call foo()
$pm = new PluginsManager('.');
foreach (
$pm as $p)
{
   
$p->class_factory('test', 1, 2)->foo();
}

?>

You may download php files at my tw.o page: http://tikiwiki.org/tiki-index.php?page=UserPagezaufi (see page attachments below)
<nospam>mike[ at ]emesdee.net</nospam>
23-Nov-2004 05:47
Excelent article here by Harry Fuecks...

http://www.sitepoint.com/print/php5-standard-library

and some auto generated documentation that could be of some use here...

http://www.php.net/~helly/php/ext/spl/index.html
mastabog at hotmail dot com
18-Aug-2004 06:41
Marcus Boerger has done a wonderful job developing the SPL. He also provided many examples using the SPL that can be found in the php5 sources. Just unpack the sources and in the ext/spl/examples directory you have some very nice ones. Thank you Marcus for all your efforts!

Now, a contribution of mine (i think it will be implemented later anyway). The RecursiveIteratorIterator could use a depth limit option. Very useful in many situations (e.g. show just the 1st subdirectory of a list of dirs). I'm sure this can be done in other ways. Here's my 2 cents:

<?php
/**
 * Limit Depth RecursiveIteratorIterator class
 *
 */
class LimitRecursiveIteratorIterator extends RecursiveIteratorIterator
{
   
protected $depth_limit;

   
/**
     * No depth limit by default
     *
    **/
   
public function __construct (Iterator $it, $mode = RIT_SELF_FIRST, $depth_limit = -1)
    {
       
parent::__construct($it, $mode);
       
$this->depth_limit = $depth_limit;
    }

   
/**
     * After the call to next() if depth is bigger than limit then
     * just skip all subIterators for that depth until depth end.
     *
    **/
   
public function next ()
    {
       
parent::next();

        if (
$this->getDepth() == $this->depth_limit)
        {
            while (
$this->getSubIterator()->valid())
               
$this->getSubIterator()->next();
           
parent::next();
        }
    }
}
?>

Then you can try this:

<?php
/**
 * Directories only filter iterator class
 *
 */
class DirectoriesOnlyIterator extends FilterIterator implements RecursiveIterator
{
   
public function __construct ($path)
    {
       
parent::__construct(new RecursiveDirectoryIterator($path));
    }

   
public function accept()
    {
        return
$this->getInnerIterator()->hasChildren();
    }

   
public function hasChildren ()
    {
        return
$this->getInnerIterator()->hasChildren();
    }
   
   
public function getChildren ()
    {
        return new
self($this->getInnerIterator()->getPathname());
    }
}

$it = new LimitRecursiveIteratorIterator(new DirectoriesOnlyIterator('c:'), RIT_SELF_FIRST, 2);

// list all dirs and 1st subdir of the c: drive (might take a while depending on how many you have)
foreach ($it as $key => $value)
{
    echo
str_repeat('    ', $it->getDepth()) . "$value\n";
}

?>

This is considerably faster than using just the RecursiveIteratorIterator and ignoring yourself in the foreach loop the values for depth > limit (i.e. if($it->getDepth() > $limit) continue;). that is because the class will still parse everything up to the last depth level of every head node.

You can then play and display nice trees (might need a while() loop or the CachingRecursiveIterator to detect end nodes/leafs). There is already an example provided by Marcus in the ext/spl/examples dir i mentioned above.

Happy SPL-ing :),
Bogdan

P.S. I think some of the classes should call rewind() at instantiation time ... If you try to put a Caching* object in a foreach loop you will lose the first/last element. Instead, you should call rewind() and then go with a while($cit->valid()) loop and using current() and key() inside it.
dave at tunasoft dot com
10-Aug-2004 10:28
There are some interfaces used here that are not documented.  It took a bit to figure this one out, but you can create your own ArrayObject type class (that is, one who's objects can be access using the array [$index] syntax).

Your class must just implement ArrayAccess.  Which has four abstract methods you must define.  For example:

<?php
   
class Collection Implements ArrayAccess{
   
       
protected $array;
       
        function
offsetExists($offset){
           
            if(isset(
$this->array[$offset])){
                return
TRUE;
            }
            else{
                return
FALSE;
            }
           
        }
       
        function
offsetGet($offset){
           
            return
$this->array[$offset];
           
        }
       
        function
offsetSet($offset, $value){
           
            if(
$offset){
               
$this->array[$offset] = $value;
            }
            else{
               
$this->array[] = $value;
            }
       
        }
       
        function
offsetUnset($offset){
       
        }
   
   
    }
?>

You'll have to jump through a couple more hoops to get foreach and print_r and the likes to behave properly.  But with just this, you can :

<?php
      $col
= new Collction();
     
$col[] = new ObjectX();
     
$col[] = new ObjectX(123);

      echo
$col[0]->name;
     
// etc.
?>
phil &ampersat; flatnet.net
18-Apr-2004 07:11
Here's a sample implementation of the RecursiveDirectoryIterator class. It prints a simple treeview of a given directory:
<?php
function recurse($it) {
   echo
'<ul>';
   for( ;
$it->valid(); $it->next()) {
       if(
$it->isDir() && !$it->isDot()) {
          
printf('<li class="dir">%s</li>', $it->current());
           if(
$it->hasChildren()) {
              
$bleh = $it->getChildren();
               echo
'<ul>' . recurse($bleh) . '</ul>';
           }
       } elseif(
$it->isFile()) {
           echo
'<li class="file">'. $it->current() . ' (' . $it->getSize(). ' Bytes)</li>';
       }
   }
   echo
'</ul>';
}

recurse(new RecursiveDirectoryIterator('D:/'));
?>

 
show source | credits | sitemap | contact | advertising | mirror sites