超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<endin_array>
Last updated: Fri, 22 Jun 2007

extract

(PHP 3>= 3.0.7, PHP 4 , PHP 5)

extract --  从数组中将变量导入到当前的符号表

说明

int extract ( array var_array [, int extract_type [, string prefix]])

本函数用来将变量从数组中导入到当前的符号表中。接受结合数组 var_array 作为参数并将键名当作变量名,值作为变量的值。对每个键/值对都会在当前的符号表中建立变量,并受到 extract_typeprefix 参数的影响。

注: 自版本 4.0.5 起本函数返回被提取的变量数目。

注: EXTR_IF_EXISTSEXTR_PREFIX_IF_EXISTS 是版本 4.2.0 中引进的。

注: EXTR_REFS 是版本 4.3.0 中引进的。

extract() 检查每个键名看是否可以作为一个合法的变量名,同时也检查和符号表中已有的变量名的冲突。对待非法/数字和冲突的键名的方法将根据 extract_type 参数决定。可以是以下值之一:

EXTR_OVERWRITE

如果有冲突,覆盖已有的变量。

EXTR_SKIP

如果有冲突,不覆盖已有的变量。

EXTR_PREFIX_SAME

如果有冲突,在变量名前加上前缀 prefix

EXTR_PREFIX_ALL

给所有变量名加上前缀 prefix。自 PHP 4.0.5 起这也包括了对数字索引的处理。

EXTR_PREFIX_INVALID

仅在非法/数字的变量名前加上前缀 prefix。本标记是 PHP 4.0.5 新加的。

EXTR_IF_EXISTS

仅在当前符号表中已有同名变量时,覆盖它们的值。其它的都不处理。可以用在已经定义了一组合法的变量,然后要从一个数组例如 $_REQUEST 中提取值覆盖这些变量的场合。本标记是 PHP 4.2.0 新加的。

EXTR_PREFIX_IF_EXISTS

仅在当前符号表中已有同名变量时,建立附加了前缀的变量名,其它的都不处理。本标记是 PHP 4.2.0 新加的。

EXTR_REFS

将变量作为引用提取。这有力地表明了导入的变量仍然引用了 var_array 参数的值。可以单独使用这个标志或者在 extract_type 中用 OR 与其它任何标志结合使用。本标记是 PHP 4.3.0 新加的。

如果没有指定 extract_type,则被假定为 EXTR_OVERWRITE

注意 prefix 仅在 extract_type 的值是 EXTR_PREFIX_SAMEEXTR_PREFIX_ALLEXTR_PREFIX_INVALIDEXTR_PREFIX_IF_EXISTS 时需要。如果附加了前缀后的结果不是合法的变量名,将不会导入到符号表中。

extract() 返回成功导入到符号表中的变量数目。

extract() 的一种可能用法是将 wddx_deserialize() 返回的结合数组中的内容导入到符号表变量中去。

例子 1. extract() 例子

<?php

/* 假定 $var_array 是 wddx_deserialize 返回的数组*/

$size = "large";
$var_array = array ("color" => "blue",
                  
"size"  => "medium",
                  
"shape" => "sphere");
extract ($var_array, EXTR_PREFIX_SAME, "wddx");

print
"$color, $size, $shape, $wddx_size\n";

?>

以上例子将产生:

blue, large, sphere, medium

$size 没有被覆盖,因为指定了 EXTR_PREFIX_SAME,这使得 $wddx_size 被建立。如果指定了 EXTR_SKIP,则 $wddx_size 也不会被建立。EXTR_OVERWRITE 将使 $size 的值为“medium”,EXTR_PREFIX_ALL 将建立新变量 $wddx_color$wddx_size$wddx_shape

必须使用结合数组,数字索引的数组将不会产生结果,除非用了 EXTR_PREFIX_ALL 或者 EXTR_PREFIX_INVALID

参见 compact()




add a note add a note User Contributed Notes
extract
dkellner
08-Dec-2003 05:33
If you are tired of always writing "EXTR_PREFIX_ALL" (which i believe is the most useful feature of extract) then you can use a function like:

  function xtract($a,$prefix) {
  foreach($a as $key=>$val) $GLOBALS["${prefix}_${key}"]=$val;
  }

and then call it like

  xtract($myarray, "my");

This, however, will NOT work when called inside a function.  The reason is the array GLOBALS which we put the extracted variables into.  (I couldn't find a way to do the same trick in functions, also I had problems determining if xtract is called from another function or not.)  So be sure to always use it outside.
moc dot aidemvu at semaj
29-Nov-2003 08:44
Be carefull when following the here-recommended process for processing class constructer func_args into properties of the class.

PHP produces some strange errors in some cases when you refer to a class attribute that was not defined in the class definiton.

In particular I have found method of non-object errors code completely removed from the class definition and object interaction and definition.  Bug hunting for this is difficult as the error source behaves as though it moves.

// similar explicit example
class MyClass {

var $defined;

function MyClass() {

 }

}

$MyObject = new MyClass;

$FirstVar = $MyObject->defined;    // works fine
$MyVar = $MyObject->undefinedVariable;  // sometimes produces the error

$MyObject->undefinedVariable = "{some value}" // this makes everything work (WHETHER OR NOT IT SHOULD WORK)

The bug really seems to occur if one instance of the class has the undeclared variable assigned, but another doesn't.
marxy at portugalmail dot pt
20-Nov-2003 08:52
I would like to extract an associative array into the properties of an object

<?
class MyClass
{
  $var property1;
  $var property2;
 
 
  function MyClass( $array )
  {
    extract( $array )
  }
}

$properties = array( 'property1'=>"red", 'property2'=>'blue')
$c = new MyClass( $propertries );
print_r( $c );
?>

This won't work cause, property1(="red") and property2(="blue") will only be available inside the constructor.

The way to do it is:
<?
class MyClass
{
 $var property1;
 $var property2;

 function MyClass( )
 {
   if( func_num_args( ) > 0  )
   {
      $array = func_get_arg( 0 );
      foreach( $array as $key => $value )
      {
          $this->$key = $value;
       }
    }
    else
     {
          die("on args in");
     }
 }

 $properties = array( 'property1'=>"red", 'property2'=>'blue')
 $c = new MyClass( $propertries );
 print_r( $c );
}
?>

This way you can create an object no knowing for sure how many init values (and order) you will have.
mina86 at tlen dot pl
19-Oct-2003 08:06
Re peppe1001 @ 01-Sep-2003 07:55:
Note that extracting $_POST, $_GET, ... vars to global varible table is sooo insecure.. It's enought to send:

Cookie: REMOTE_ADDR=127.0.0.1

header to make your script think that request was made from localhost.. It is strongly recommended that you use $_* arrays but if you realy want to have $_* vars extracted better use something like:

<?php
if (phpversion() >= 4.2) {
   extract($_POST, EXTR_PREFIX_ALL, 'VARS_');
  extract($_GET, EXTR_PREFIX_ALL, 'VARS_');
   extract($_SERVER, EXTR_PREFIX_ALL, 'SERVER_');
   extract($_FILES, EXTR_PREFIX_ALL, 'FILES_');
   extract($_ENV, EXTR_PREFIX_ALL, 'ENV_');
  extract($_COOKIE, EXTR_PREFIX_ALL, 'COOKIE_');
   extract($_SESSION, , EXTR_PREFIX_ALL, 'SESSION_');
}
?>

However then I don't see any reason to do this..
sdibb at myway dot com
13-Sep-2003 03:30
Be sure to use parentheses, otherwise you'll get a unexpected T_VARIABLE error.

I lost a few hairs trying to figure that one out.

extract ($array) not extract $array
peppe1001 at hotmail dot com
01-Sep-2003 07:55
If you have problems with 'GET or 'POST' variables with the new version of PHP then you can use this for all versions

if ( phpversion() >= "4.2.0")
   {
   extract($_POST);
  extract($_GET);
   extract($_SERVER);
   extract($_FILES);
  extract($_ENV);
   extract($_COOKIE);
extract($_SESSION);
   }
blistedus(a)yahoo()com
26-Sep-2002 02:15
If you're using extract with mysql_fetch_assoc, and only grabbing one line you can nestle it:
extract(mysql_fetch_assoc(mysql_query("SELECT * FROM table")));

If you're doing this in a while statement it will fail.  Using something like...

$mysql_data = mysql_query("SELECT * FROM everywhere");
while (extract(mysql_fetch_assoc($mysql_data))) {
 .. }

...will not work, while using...

while ($row = mysql_fetch_assoc($mysql_data)) {
 extract($row);
 ...
}

...will.  The only reason I find as an explination for this is annoyance.
marc dot webb at sinclair dot edu
16-Aug-2002 12:36
If you ever want to get lazy when passing variables to functions, you might
try this procedure which dumps all defined variables into one array,
passes the one array to a function and splits it back into the original
variables:

function my_function($all_vars)
{
    extract($all_vars);
    //meat of function
}

$all_vars=get_defined_vars();
my_function($all_vars);

This is a lot easier than passing 10 arguments and having to type them for
the function definition and all the function calls in your program.

This also helps if you generate variable numbers of arguments, haven't
planned ahead for them, and the beta code is due by 5:00.
phplist at jzdev dot com
07-Mar-2002 02:05
Be careful when using extract() on an array that may contain null values.

Say you're in a loop and overwrite the vars each time through. You'd expect the vars to contain whatever value you would get if you accessed the array directly. This doesn't happen. Null values won't overwrite the last value.

Example:
Datbase contains
FieldA FieldB
10      20
NULL  50
25     20

while ($row = mysql_fetch_array($rs)) {
 extract($row, EXTR_PREFIX_ALL, "IN");
 echo $IN_FieldA.", ".$IN_FieldB."\n";
}

Output:
10, 20
10, 50
25, 20
alexphpdoc at blamey dot freeserve dot co dot uk
13-Apr-2000 11:23
When the prefix is used an underscore ('_') is inserted, i.e.

extract(array("var" => "val"), EXTR_PREFIX_ALL, "pre");

will create a variable called $pre_var NOT $prevar.
(This is with PHP 4.0b3pl1)

<endin_array>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22