下载两次了,都这样,原来的天刀下载器打不开不小心给卸载了,重下就这样了

php中substr()函数参数说明及用法实例
投稿:shichen2014
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了php中substr()函数参数说明及用法,以实例形式深入分析了substr()函数中的各个参数的含义,并举例说明了其对应的用法,需要的朋友可以参考下
本文实例讲述了php中substr()函数参数说明及用法。分享给大家供大家参考。具体如下:
string substr(string $string ,int $start [, int $length ]),它可以用于在一个较长的字符串中查找匹配的字符串或字符,$string为所要处理的字符串,$start为开始选取的位置,$length为要选取的长度.
$length 为正数据从左向右读取字符.
$length 为负数时就右向左读取字符.
string 必需,规定要返回其中一部分的字符串.
start 必需,规定在字符串的何处开始.
charlist 可选,规定要返回的字符串长度,默认是直到字符串的结尾.
正数 - 在字符串的指定位置开始
负数 - 在从字符串结尾的指定位置开始
0 - 在字符串中的第一个字符处开始
PHP实例代码如下:
代码如下:$rest_1 = substr("abcdef", 2); // returns "cdef"
$rest_2 = substr("abcdef", -2); // returns "ef"
$rest1 = substr("abcdef", 0, 0); // returns ""
$rest2 = substr("abcdef", 0, 2); // returns "ab"
$rest3 = substr("abcdef", 0, -1); // returns "abcde"
$rest4 = substr("abcdef", 2,0); // returns ""
$rest5 = substr("abcdef", 2,2); // returns "cd"
$rest6 = substr("abcdef", 2, -1); // returns "cde"
$rest7 = substr("abcdef", -2,0); // returns ""
$rest8 = substr("abcdef", -2,2); // returns "ef"
$rest9 = substr("abcdef", -2,-1); // returns "e"
希望本文所述对大家的PHP程序设计有所帮助。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具PHP代码优化之成员变量获取速度对比
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了PHP中类的成员变量在4种方式下的获取速度对比,并详细分析了其中的原因,需要的朋友可以参考下
有如下4个代码示例,你认为他们创建对象,并且获得成员变量的速度排序是怎样的?
1:将成员变量设置为public,通过赋值操作给成员变量赋值,直接获取变量 代码如下:&?phpclass Foo {&&& public $}$data = new F$data-&id = 10;echo $data-&?&2:将成员变量设置为public,通过构造函数设置成员变量的值,直接获取变量 代码如下:&?phpclass Foo2 {&public $&public function __construct($id) {&&$this-&id = $&}}
$data = new Foo2(10);echo $data-&?&3:将成员变量设置为protected,通过构造函数设置成员变量的值,通过魔术方法获取变量 代码如下:&?phpclass Foo3 {&protected $&public function __construct($id) {&&$this-&id = $&}
&public function getId() {&&return $this-&&}}$data = new Foo3(10);echo $data-&getId();?&4:将成员变量设置为protected,通过构造函数设置成员变量的值,通过成员方法获取变量&?phpclass Foo4 {& protected $& public function __construct($id) {&& $this-&id = $& }
& public function __get($key) {&& return $this-&& }}$data = new Foo4(10);echo $data-&?&按执行速度快慢排序: 1243咱们先看其opcode:1: 代码如下:1& ZEND_FETCH_CLASS&4 &:4 &'Foo'2& NEW&&&&& &&&$5&:43& DO_FCALL_BY_NAME&&&0&&&&&&&&& 4& ASSIGN&&&& &&&&!0, $55& ZEND_ASSIGN_OBJ&&&!0, 'id'6& ZEND_OP_DATA&&&&107& FETCH_OBJ_R&&&$9&!0, 'id'8& ECHO&&&&&&& &&&&$92: 代码如下:1& ZEND_FETCH_CLASS&4 &:10&'Foo2'2& NEW&&&&&&&&&&&& &&$11&:103& SEND_VAL&&&&&&& &&&104& DO_FCALL_BY_NAME&&1 5& ASSIGN&&& &&&&!1, $116& FETCH_OBJ_R&&&$14&!1, 'id'7& ECHO&&&&&&& &&&&$143: 代码如下:1& ZEND_FETCH_CLASS&4 &:15&'Foo3'2& NEW&&&&&&&& &&&$16&:153& SEND_VAL&&&& &&&104& DO_FCALL_BY_NAME&&&1&&&&&&&&& 5& ASSIGN& &&& &&&!2, $166& ZEND_INIT_METHOD_CALL&!2, 'getId'7& DO_FCALL_BY_NAME&&0 &$20&&&& 8& ECHO&&&&&& &&&&$204: 代码如下:1& ZEND_FETCH_CLASS&4& :21&'Foo4'2& NEW&&&&&&&&& &&$22&:213& END_VAL&&&&& &&&104& DO_FCALL_BY_NAME&&1&&&&&&&&& 5& ASSIGN&&&&&&& &&&!3, $226& FETCH_OBJ_R& &&$25 !3, 'id'7&& ECHO& &&&&$25根据上面的opcode,参照其在zend_vm_execute.h文件对应的opcode实现,我们可以发现什么?一、PHP内核创建对象的过程分为三步:ZEND_FETCH_CLASS 根据类名获取存储类的变量,其实现为一个hashtalbe EG(class_table) 的查找操作NEW 初始化对象,将EX(call)-&fbc指向构造函数指针。调用构造函数,其调用和其它的函数调用是一样,都是调用zend_do_fcall_common_helper_SPEC二、魔术方法的调用是通过条件触发的,并不是直接调用,如我们示例中的成员变量id的获取(zend_std_read_property),其步骤为:获取对象的属性,如果存在,转第二步;如果没有相关属性,转第三步从对象的properties查找是否存在与名称对应的属性存在,如果存在返回结果,如果不存在,转第三步如果存在__get魔术方法,则调用此方法获取变量,如果不存在,报错回到排序的问题:一、第一个和第二个的区别是什么?第二个的opcode比第一个要少,反而比第一个要慢一些,因为构造函数多了参数,多了一个参数处理的opcode。参数处理是一个比较费时的操作,当我们在做代码优化时,一些不必要的参数能去掉就去掉;当一个函数有多个参数时,可以考虑通过一个数组将其封装后传递进来。二、为啥第三个最慢?因为其获取参数其本质上是一次对象成员方法的调用,方法的调用成本高于变量的获取三、为啥第四个比第三个要快?因为第四个的操作实质上获取变量,只不过其内部实现了魔术方法的调用,相对于用户定义的方法,内部函数的调用的效率会高。因此,当我们有一些PHP内核实现的方法可以调用时就不要重复发明轮子了。四、为啥第四个比第二个要慢?因为在PHP的对象获取变量的过程中,当成员变量在类的定义不在在时,会去调用PHP特有的魔术方法__get,多了一次魔术方法的调用。总结一下:1.使用PHP内置函数2.并不是事必面向对象(OOP),面向对象往往开销很大,每个方法和对象调用都会消耗很多内存。3.尽量少用魔术方法 -- 除非有必要,不要用框架,因为框架都有大量的魔术方法使用。4.在性能优先的应用场景中,将成员变量不失为一种比较好的方法,当你需要用到OOP时。5.能使用PHP语法结构的不要用函数,能使用内置函数的不要自己写,能用函数的不要用对象
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具php中count()函数的作用?
php count函数使用
来源:网络
关键字: php count
更新时间:
延伸:本文除了聚合《php中count()函数的作用?》,免费提供的有关php count和php count函数使用的内容之一,已有不少的网友认为此答案对自己有帮助!
网友1的回答
如果你单纯是要计算查询出的行数 用$num = mysql_num_rows($R1);就可以了 如网友2的回答
搜了下。参考资料可以说明了。应该算了1,2,a,b,c,d,e。 我比较少用COUNT_RECURS网友3的回答
$db-&fetch_array这个封装函数里应该该是用的mysql_fetch_array,你需要网友4的回答
count 函数 中 如果 mode 被设置为 COUNT_RECURSIVE(或 1),则会递归底网友5的回答
mysql_query 的返回值不是查询出来的结果的条数,而是返回本次查询是否成功。 如果失败则返回网友6的回答
$tag2 = array_unique($tag)中$tag2,不包含空元素(你print_r($网友7的回答
&?php $pens=array( &p1&=&array(&brand&=&&aaa&,&col网友8的回答
这是个自定义函数,根据上下文,应该是是用于计算页面点击量的,并且以文本记录点击数据。。网友9的回答
网友7的回答
猜你感兴趣
相关关键词Keyboard Shortcuts?
Next menu item
Previous menu item
Previous man page
Next man page
Scroll to bottom
Scroll to top
Goto homepage
Goto search(current page)
Focus search box
Change language:
Brazilian Portuguese
Chinese (Simplified)
有时候使用可变变量名是很方便的。就是说,一个变量的变量名可以动态的设置和使用。一个普通的变量通过声明来设置,例如:
一个可变变量获取了一个普通变量的值作为这个可变变量的变量名。在上面的例子中
hello 使用了两个美元符号($)以后,就可以作为一个可变变量的变量了。例如:
这时,两个变量都被定义了:$a 的内容是“hello”并且
$hello 的内容是“world”。因此,以下语句:
与以下语句输出完全相同的结果:
它们都会输出:hello world。
要将可变变量用于数组,必须解决一个模棱两可的问题。这就是当写下
时,解析器需要知道是想要
作为一个变量呢,还是想要
作为一个变量并取出该变量中索引为 [1]
的值。解决此问题的语法是,对第一种情况用
${$a[1]},对第二种情况用
${$a}[1]。
类的属性也可以通过可变属性名来访问。可变属性名将在该调用所处的范围内被解析。例如,对于
$foo->$bar 表达式,则会在本地范围来解析 $bar
并且其值将被用于 $foo 的属性名。对于 $bar
是数组单元时也是一样。
也可使用花括号来给属性名清晰定界。最有用是在属性位于数组中,或者属性名包含有多个部分或者属性名包含有非法字符时(例如来自
Example #1 可变属性示例
&?phpclass&foo&{&&&&var&$bar&=&'I&am&bar.';&&&&var&$arr&=&array('I&am&A.',&'I&am&B.',&'I&am&C.');&&&&var&$r&&&=&'I&am&r.';}$foo&=&new&foo();$bar&=&'bar';$baz&=&array('foo',&'bar',&'baz',&'quux');echo&$foo-&$bar&.&"\n";echo&$foo-&$baz[1]&.&"\n";$start&=&'b';$end&&&=&'ar';echo&$foo-&{$start&.&$end}&.&"\n";$arr&=&'arr';echo&$foo-&$arr[1]&.&"\n";echo&$foo-&{$arr}[1]&.&"\n";?&
以上例程会输出:
注意,在 PHP 的函数和类的方法中,不能用作可变变量。$this
变量也是一个特殊变量,不能被动态引用。
&?php& $Bar = "a";& $Foo = "Bar";& $World = "Foo";& $Hello = "World";& $a = "Hello";& $a; $$a; $$$a; $$$$a; $$$$$a; $$$$$$a; $$$$$$$a; ?&
It may be worth specifically noting, if variable names follow some kind of "template," they can be referenced like this:&?php$nameTypes& & = array("first", "last", "company");$name_first&& = "John";$name_last& & = "Doe";$name_company = "PHP.net";foreach($nameTypes as $type)& print ${"name_$type"} . "\n";print "$name_first\n$name_last\n$name_company\n";?&This is apparent from the notes others have left, but is not explicitly stated.
Another use for this feature in PHP is dynamic parsing..&
Due to the rather odd structure of an input string I am currently parsing, I must have a reference for each particular object instantiation in the order which they were created.& In addition, because of the syntax of the input string, elements of the previous object creation are required for the current one.&
Normally, you won't need something this convolute.& In this example, I needed to load an array with dynamically named objects - (yes, this has some basic Object Oriented programming, please bare with me..)
&?php
&& include("obj.class");
&& $object_array = array();
&& foreach ($input_array as $key=&$value){
& & & $obj = "obj".$key;
& & & && $$obj = new Obj($value, $other_var);
& & & && Array_Push($object_array, $$obj);
& & & }
Now, we can use basic array manipulation to get these objects out in the particular order we need, and the objects no longer are dependant on the previous ones.
I haven't fully tested the implimentation of the objects.& The& scope of a variable-variable's object attributes (get all that?) is a little tough to crack.& Regardless, this is another example of the manner in which the var-vars can be used with precision where tedious, extra hard-coding is the only alternative.
Then, we can easily pull everything back out again using a basic array function: foreach.
&?php
foreach($array as $key=&$object){
& & & echo $key." -- ".$object-&print_fcn()." &br/&\n";
Through this, we can pull a dynamically named object out of the array it was stored in without actually knowing its name.
PHP actually supports invoking a new instance of a class using a variable class name since at least version 5.2&?phpclass Foo {&& public function hello() {& & & echo 'Hello world!';&& }}$my_foo = 'Foo';$a = new $my_foo();$a-&hello(); ?&Additionally, you can access static methods and properties using variable class names, but only since PHP 5.3&?phpclass Foo {&& public static function hello() {& & & echo 'Hello world!';&& }}$my_foo = 'Foo';$my_foo::hello(); ?&
It's also valuable to note the following:&?php${date("M")} = "Worked";echo ${date("M")};?&This is perfectly legal, anything inside the braces is executed first, the return value then becomes the variable name. Echoing the same variable variable using the function that created it results in the same return and therefore the same variable name is used in the echo statement. H).
This is a handy function I put together to allow variable variables to be used with arrays.To use the function, when you want to reference an array, send it in the form 'array:key' rather than 'array[key]'.For example:&?phpfunction indirect ($var, $value)& && {&& $var_data = $explode($var, ':');&& if (isset($var_data[1]))&& {& & & ${$var_data[0]}[$var_data[1]] = $value;&& }&& else&& {& & & ${$var_data[0]} = $value;&& }}$temp_array = array_fill(0, 4, 1);$temp_var = 1;$int_var_list = array('temp_array[2]', 'temp_var');while (list($key, $var_name) = each($int_var_list)){&& $$var_name = 0;}var_dump($temp_array);echo '&br&';var_dump($temp_var);echo '&br&';$int_var_list = array('temp_array:2', 'temp_var');while (list($key, $var_name) = each($int_var_list)){&& indirect($var_name, 2);}var_dump($temp_array);echo '&br&';var_dump($temp_var);echo '&br&';?&
In 5.4 "Dynamic class references require the fully qualified class name (with the namespace in it) because at runtime there is no information about the current namespace." is still true.Neither simple class name nor containing subnamespace works.Initial source:
These are the scenarios that you may run into trying to reference superglobals dynamically. Whether or not it works appears to be dependent upon the current scope.&?php$_POST['asdf'] = 'something';function test() {& & $string = '_POST';& & var_dump(${$string});& & var_dump(${'_POST'});& & global ${$string};& & var_dump(${$string});}$string = '_POST';var_dump(${$string});test();?&
Adding an element directly to an array using variables:&?php$tab = array("one", "two", "three") ;$a = "tab" ;$$a[] ="four" ; print_r($tab) ;?&will issue this error:Fatal error: Cannot use [] for readingThis is not a bug, you need to use the {} syntax to remove the ambiguity.&?php$tab = array("one", "two", "three") ;$a = "tab" ;${$a}[] =& "four" ; print_r($tab) ;?&
You may think of using variable variables to dynamically generate variables from an array, by doing something similar to: -&?php foreach ($array as $key =& $value)
{& $$key= $value; }?&This however would be reinventing the wheel when you can simply use: &?phpextract( $array, EXTR_OVERWRITE);?&Note that this will overwrite the contents of variables that already exist.Extract has useful functionality to prevent this, or you may group the variables by using prefixes too, so you could use: -EXTR_PREFIX_ALL&?php$array =array("one" =& "First Value","two" =& "2nd Value","three" =& "8"& & & & & & & & );& & & & && extract( $array, EXTR_PREFIX_ALL, "my_prefix_");&& ?&This would create variables: -$my_prefix_one $my_prefix_two$my_prefix_threecontaining: -"First Value", "2nd Value" and "8" respectively
&?php$a = 'variable-name';$$a = 'hello';echo $variable-name . ' ' . $$a; ?&For a particular reason I had been using some variable names with hyphens for ages. There was no problem because they were only referenced via a variable variable. I only saw a parse error much later, when I tried to reference one directly. It took a while to realise that illegal hyphens were the cause because the parse error only occurs on assignment.
There is no need for the braces for variable object names...they are only needed by an ambiguity arises concerning which part of the reference is variable...usually with arrays.
&?php
class Schlemiel {
var $aVar = "foo";
}
$schlemiel = new Schlemiel;
$a = "schlemiel";
echo $$a-&aVar;
?&
This code outputs "foo" using PHP 4.0.3.
Hope this helps...
- Jordan
Note that normal variable variables will not be parsed in double-quoted strings. You'll have to use the braces to make it work, to resolve the ambiguity. For example:
&?php
$varname = "foo";
$foo = "bar";
print $$varname;& print "$$varname";& print "${$varname}"; ?&
Variable variables techniques do not work when one of the "variables" is a constant.& The example below illustrates this.& This is probably the desired behavior for constants, but was confusing for me when I was trying to figure it out.& The alternative I used was to add the variables I needed to the $GLOBALS array instead of defining them as constants.
define("DB_X_NAME","database1");
define("DB_Y_NAME","database2");
$DB_Z_NAME="database3";
function connectTo($databaseName){
global $DB_Z_NAME;
$fullDatabaseName="DB_".$databaseName."_NAME";
return ${$fullDatabaseName};
print "DB_X_NAME is ".connectTo("X")."&br&";
print "DB_Y_NAME is ".connectTo("Y")."&br&";
print "DB_Z_NAME is ".connectTo("Z")."&br&";
?&
[Editor Note: For variable constants, use constant() --Philip]
One interesting thing I found out: You can concatenate variables and use spaces. Concatenating constants and function calls are also possible.
&?php
define('ONE', 1);
function one() {
& & return 1;
}
$one = 1;
${"foo$one"} = 'foo';
echo $foo1; ${'foo' . ONE} = 'bar';
echo $foo1; ${'foo' . one()} = 'baz';
echo $foo1; ?&
This syntax doesn't work for functions:
&?php
$foo = 'info';
{"php$foo"}(); $func = "php$foo";
$func();
?&
Note: Don't leave out the quotes on strings inside the curly braces, PHP won't handle that graciously.
By the way...
Variable variables can be used as pointers to objects' properties:
&?php
class someclass {
& var $a = "variable a";
& var $b = "another variable: b";
& }
$c = new someclass;
$d = "b";
echo $c-&{$d};
?&
outputs: another variable: b
Variable Class Instantiation with Namespace Gotcha:Say you have a class you'd like to instantiate via a variable (with a string value of the Class name)&?phpclass Foo { & & public function __construct() & & { & & & & echo "I'm a real class!" . PHP_EOL;& & }}$class = 'Foo';$instance = new $class;?&The above works fine UNLESS you are in a (defined) namespace. Then you must provide the full namespaced identifier of the class as shown below. This is the case EVEN THOUGH the instancing happens in the same namespace. Instancing a class normally (not through a variable) does not require the namespace. This seems to establish the pattern that if you are using an namespace and you have a class name in a string, you must provide the namespace with the class for the PHP engine to correctly resolve (other cases: class_exists(), interface_exists(), etc.) &?phpnamespace MyNamespace;class Foo { & & public function __construct() & & { & & & & echo "I'm a real class!" . PHP_EOL;& & }}$class = 'MyNamespace\Foo';$instance = new $class;?&
This is somewhat redundant, but I didn't see an example that combined dynamic reference of *both* object and attribute names.
Here's the code:
&?php
class foo
{
& & var $bar;
& & var $baz;
& & function foo()
& & {
& & & & $this-&bar = 3;
& & & & $this-&baz = 6;
& & }
}
$f = new foo();
echo "f-&bar=$f-&bar& f-&baz=$f-&baz\n";
$obj& = 'f';
$attr = 'bar';
$val& = $$obj-&{$attr};
echo "obj=$obj& attr=$attr& val=$val\n";
?&
And here's the output:
f-&bar=3& f-&baz=6
$obj=f& $attr=bar& $val=3
Sometimes you might wish to modify value of an existing variable by its name. This is easily accomplishable with a combination of using "passing by reference" and "variable variables".$first_var = 1;$second_var = 2;$third_var = 3;$which_one = array_rand('first', 'second', 'third');//Let's consider the result is "second".$modifier = $$which_& //Now $modifier has value 2.$modifier++; //Now $modifier's value is 3.echo $second_ //Prints out 2//Consider we wish to modify the value of $second_var$modifier = &$$which_& //Simply passing by reference$modifier++; //Now value of $second_var is 3 too.echo $second_ //Prints out 3It's that simple!
A good example of the use of variable variables name. Imagine that you want to modify at the same time a list of more than one record from a db table.
1) You can easily create a dynamic form using PHP. Name your form elements using a static name and the record id
ex: &input name="aninput&?php echo $recordid?&" which gives in the output something like &input name="aninput15"&
2)You need to provide to your form action/submit script the list of records ids via an array serialized and urlencoded via an hidden field (to decode and un serialize once in the submit script)
3) In the script used to submit you form you can access the input value by using the variable ${'aninput'.$recordid} to dynamically create as many UPDATE query as you need
[Editor Note: Simply use an array instead, for example: &input name="aninput[&?php echo $recordid?&]" And loop through that array. -Philip]
Parsing and retrieving a value from superglobals, by a specified order, looping until it find one :
&?php
function GetInputString($name, $default_value = "", $format = "GPCS")
& & {
& & & & $format_defines = array (
& & & & 'G'=&'_GET',
& & & & 'P'=&'_POST',
& & & & 'C'=&'_COOKIE',
& & & & 'S'=&'_SESSION',
& & & & 'R'=&'_REQUEST',
& & & & 'F'=&'_FILES',
& & & & );
& & & & preg_match_all("/[G|P|C|S|R|F]/", $format, $matches); foreach ($matches[0] as $k=&$glb)
& & & & {
& & & & & & if ( isset ($GLOBALS[$format_defines[$glb]][$name]))
& & & & & & {& &
& & & & & & & & return $GLOBALS[$format_defines[$glb]][$name];
& & & & & & }
& & & & }
& & &&
& & & & return $default_value;
& & }
?&
hi, i handling multi-array with like this:
i use this for some classes with direct access to $__info array. and i have some config_{set|get} static functions without this class, but handling is the same.
i'm not testing this piece of code for benchmark and high load.
&?php
class __info {
& private $__info=array();
& public function __s($value=null, $id='')
& & {
& & & & if ($id == '')
& & & & & & return false;
& & & & $id='[\''.$id.'\']';
& & & & for ($i=2, $max=func_num_args(), $args=func_get_args(); $i&$max; $i++)
& & & & & & $id.='[\''.$args[$i].'\']';
& & & & eval('
& & & & & & if (isset($this-&__info'.$id.')) {
& & & & & & & & // debug || vyjimka
& & & & & & }
& & & & & & $this-&__info'.$id.'=$
& & & & ');
& & & & return true;
& & }
& public function __g($id)
& & {
& & & & $uid='';
& & & & for ($i=0, $max=func_num_args(), $args=func_get_args(); $i&$max; $i++)
& & & & & & $uid.="[\'".$args[$i]."\']";
& & & & return eval('
& & & & & & if (isset($this-&__info'.$uid.')) {
& & & & & & & & return $this-&__info'.$uid.';
& & & & & & } else {
& & & & & & & &
& & & & & & }
& & & & & & // debug || vyjimka
& & & & ');
& & & & return false;
& & }
?&
Parse an imported string e.g. from a database for php variable names and replace them with their values.example:In the String "Dear $firstname $lastname, welcome to our Homepage" the variables shall be replaced with the respective values.&?php$welcome = getImportedString();$firstname = "David";$lastname = "Forger";echo $welcome;function replaceVars($match) { & & && return $GLOBALS[$match[1]]; }& & & & $welcome = preg_replace_callback('/\$(\w+)/i', "replaceVars", $welcome);echo $welcome;?&
A static variable variable sounds like an oxymoron and indeed cannot exist. If you define:
&?php
$var = "ciao";
static $$var = 0;
?&
you get a parse error.
Regards,
I have a HTML form that has a dynamic number of fields (for entry of collected data it adds a new field each time) and would like to use the variable variable on _POST.& This way, I could increment the field name value with a loop limit when say 100 fields are reached (the max for the form.)Below is the solution I came up with to work around it:&?php& & & & $MaxRows=100;& & & & $NumbersOfTime=0;& & & & extract ($_POST,EXTR_PREFIX_ALL,'pos');& & & & for ($i = 1; $i &= $MaxRows; $i = $i + 1)& & & & {& & & & & & & & $tmp = "pos_TimeRecorded{$i}";& & & & & & & & if (isset($$tmp))& & & & & & & & {& & & & & & & & & & & & $TimeRecorded[$i]=$$tmp;& & & & & & & & }& & & & & & & & else& & & & & & & & {& & & & & & & & & & & & $NumbersOfTime=$i-1;& & & & & & & & & & & && & & & & & & & }& & & & }?&
The example given in the php manual is confusing!I think this example it's easier to understand: &?php$var_name = "new_variable_1"; $$var_name& = "value 1"; echo "VARIABLE: " . $var_name;echo "&br /&";echo "VALUE: " . $$var_name;?&The OUTPUT is:VARIABLE: new_variable_1VALUE: value 1 You can also create new variables in a loop:&?phpfor( $i = 1; $i & 6; $i++ ){$var_name[] = "new_variable_" . $i; }${$var_name[0]}& = "value 1"; ${$var_name[1]}& = "value 2"; ${$var_name[2]}& = "value 3"; ${$var_name[3]}& = "value 4"; ${$var_name[4]}& = "value 5"; echo "VARIABLE: " . $var_name[0] . "\n";echo "&br /&";echo "VALUE: " . ${$var_name[0]};?&The OUTPUT is:VARIABLE: new_variable_1VALUE: value 1
If $something is 'myvar' then you can use $obj-&{"_$something"} to get the value of $obj-&_myvar without having to use eval.
This example may help to overcome the limitation on $this.Populate automatically fields of an object form a $_GET variable.&?phpclass pp{&& var $prop1=1,$prop2=2,$prop3=array(3,4,5);&& function fun1(){& & & $vars=get_class_vars('pp');& & & while(list($var,$value)=each($vars)){& & & & & & && $ref=& $this-&$var;& & & & & & && $ref=$_GET[$var];& & & } var_dump($this);&& }}$_GET['prop1']="uno";$_GET['prop2']="dos";$_GET['prop3']=array('tres','cuatro','cinco','seis');$p=new pp();$p-&fun1();?&output is ...object(pp)#1 (3) {& ["prop1"]=&& &string(3) "uno"& ["prop2"]=&& &string(3) "dos"& ["prop3"]=&& &array(4) {& & [0]=&& & string(4) "tres"& & [1]=&& & string(6) "cuatro"& & [2]=&& & string(5) "cinco"& & [3]=&& & string(4) "seis"& }}
On the topic of variable variables with arrays, I have a simple function that solves the issue. It works for both indexed and associative arrays, and allows use with superglobals.
&?php
function VariableArray($arr, $string)
& & {
& & preg_match_all('/\[([^\]]*)\]/', $string, $arr_matches, PREG_PATTERN_ORDER);
& &
& & $return = $arr;
& & foreach($arr_matches[1] as $dimension)
& & & & {
& & & & $return = $return[$dimension];
& & & & }
& & & &
& & return $return;
& & }
$test = array('one' =& 'two', 'four' =& array(8));
$foo = 'test';
$bar = $$foo;
$baz = "[one]";
$var = VariableArray($bar, $baz); $baz = "[four][0]";
$var = VariableArray($bar, $baz); ?&
You can simply pass in a superglobal as the first argument. Note for associative arrays don't put quotes inside the square braces unless you adjust the regexp to accept it. I wanted to keep it simple.
You can also use variable variables and the string concat operator to generate suffixed (or prefixed) variables based on a base name.
For instance, if you wanted to dynamically generate this series of variables:
base1_suffix1
base1_suffix2
base2_suffix1
base2_suffix2
base3_suffix1
base3_suffix2
You can do this:
&?php
$bases = array('base1', 'base2', 'base3');
$suffixes = array('suffix1', suffix2);
foreach($bases as $base) {
& & foreach($suffixes as $suffix) {
& & & & ${$base.$suffix} = "whatever";
& & & & }
}
?&
The 'dollar dereferencing' (to coin a phrase) doesn't seem to be limited to two layers, even without curly braces.& Observe:
&?php
$one = "two";
$two = "three";
$three = "four";
$four = "five";
echo $$$$one; ?&
This works for L-values as well.& So the below works the same way:
&?php
$one = "two";
$$one = "three";
$$$one = "four";
$$$$one = "five";
echo $$$$one; ?&
NOTE: Tested on PHP 4.2.1, Apache 2.0.36, Red Hat 7.2
You can use constants in variable variables, like I show below. This works fine:
&?php
define("TEST","Fuchs");
$Fuchs = "Test";
echo TEST . "&BR&";
echo ${TEST};
?&
Fuchs
Test
While not relevant in everyday PHP programming, it seems to be possible to insert whitespace and comments between the dollar signs of a variable variable.& All three comment styles work. This information becomes relevant when writing a parser, tokenizer or something else that operates on PHP syntax.&?php& & $foo = 'bar';& & $& & $foo = 'magic';& & echo $bar; ?&Behaviour tested with PHP Version 5.6.19
If you want to use a variable value in part of the name of a variable variable (not the whole name itself), you can do like the following:&?php$price_for_monday = 10;$price_for_tuesday = 20;$price_for_wednesday = 30;$today = 'tuesday';$price_for_today = ${ 'price_for_' . $today};echo $price_for_today; ?&
I've found this useful, particula&?php$string = "foo";${$string}_bar = "";?&
a tiny code to set variables if they don't have value yet:&?php& & function setvar($n,$v){global$$n;if(!isset($$n))$$n=$v;}?&this works under any scope, even when called inside another function!
In this example, I have the variable $city.To store the variable $city inside another variable:&?php$city = 'New York';$var_container = 'city'; echo "CONTAINER's var: " . $var_container;echo "&br /&";echo "CONTAINER's value: " . $$var_container;echo "&br /&";echo "VAR city: " . $city;?&The OUTPUT is:CONTAINER's var: cityCONTAINER's value: New YorkVAR city: New York
For a long time I've been trying to use variable variables to figure out how to store and retrieve multi-dimensional arrays in a MySQL dbase. For instance, a config setting stored in a complex array might resemble the below:&?php $config['modules']['module_events']['settings']['template']['name'] = 'List Page'; ?&The most obvious way for storing this info in a dbase (discounting XML/JSON) is to store a "path" (of the nesting) and a "value" in a database record:'modules,module_events,settings,template,name' = 'List Page'But storing it is only part of the problem. PHP variable variables are no use to try and interpret string representations of arrays, eg it will see the string representation of a nested array such as config['modules']['module_events'] as a single variable called 'config[modules][module_events]', so loops that parse the "path" into a variable variable don't help.So here is a little function that parses an array of "paths" and "value" strings (eg from a dbase) into a multi-dimensional nested array.&?phpfunction multiArrayMe($input_array) {& & $output_array = array();& & if (!is_array($input_array)) {& & & & return false;& & }& & foreach ($input_array AS $key1 =& $val1) {& & & & & & & & $temp1 = explode(',',$key1);& & & & if (!is_array($temp1)) {& & & & & && & & & }& & & & krsort($temp1);& & & & $temp2 = $val1;& & & & foreach($temp1 AS $val2) {& & & & & & if ($val2===false) {& & & & & & & && & & & & & }& & & & & & $temp2 = array($val2 =& $temp2);& & & & }& & & & $output_array = array_merge_recursive($output_array,$temp2);& & }& & return $output_array;}?&
You can simple access Globals by variable variables in functions, example:&?phpfunction abc() {& & $context = '_SESSION';& & global $$context;& & if(isset($$context)) {& & & & var_dump($$context);& & }}abc();?&
Multidimensional variable variables.& If you want to run the below as one big program, you'll have to undefine $foo in between assignments.
$foo = "this is foo.";
$ref = "foo";
print $$ref;
$foo[1]['a_z'] = "this is foo[1][a_z].";
$ref = "foo[1][a_z]";
print $$ref;
$foo = "this is foo.";
$ref = "foo";
$erf = eval("return \$$ref;");
print $erf;
$foo[1]['a_z'] = "this is foo[1][a_z].";
$ref = "foo[1][a_z]";
$erf = eval("return \$$ref;");
print $erf;
?&
Returning values from a multidimensional array based using variable variablesand infinite key depthI banged my head against this but could not find a way in language structure orin functions to retreive a value from a multidimensional array where the keypath is known as a variable string. I considered some sort of recursivefunction, but it seemed cumbersome for what should be a one-liner.My solution uses eval() to return the array value:&?php$geolocation = array("ip"=&"127.0.0.1", "location" =& array("city" =&"Knoxville", "state_province" =& "TN", "country" =& "USA"));print_r($geolocation); =& Knoxville [state_province] =& TN [country] =& USA ) )$key = "ip";$result = $geolocation[$key];print_r($result); $key = "location"; $result = $geolocation[$key];print_r($result); [country] =& USA )$key = "location['city']";$key = "['location']['city']";['city']$key = "['location']['city']";$result = eval('echo $geolocation'."$key;");print_r($result); ?&
Unlike as stated near the bottom of this thread, using variables to point to an object does not always work. In my case, that is the object returned from `new SimpleXMLElement($xmlstr)`.Once my nodes got 3 and 4 deep to access customer information from orders, I knew something drastic had to be done.&?php$xmlstr ="&xml&&foo&&bar&&you&Blah&/you&&/bar&&/foo&&/xml&";$xml=SimpleXMLElement($xmlstr);$lvl1="\$xml-&foo";echo n($lvl1."-&bar-&you");function n($node){ & & global $xml;& & return eval("return $node;");& }?&
I found another undocumented/cool feature: variable member variables in classes. It's pretty easy:
&?php
class foo {
& function bar() {
& & $bar1 = "var1";
& & $bar2 = "var2";
& & $this-&{$bar1}= "this ";
& & $this-&{$bar2} = "works";
& }
}
$test = new foo;
$test-&bar();
echo $test-&var1 . $test-&var2;
?&
This is an extremely handy use for variable variables especially when dealing with direct data modeling.& This will allow you to automatically set object properties based on a query result. When new fields are added to the table, the class will receive these properties automatically. This is great for maintaining user data or other large tables. Your property names will be bound to your column name in the database, making maintenance worry free. This method uses $this-&{$var} for the variable variable creation.&?phpclass testTableData() {& & function testTableData(){& & & & & $query = "SELECT * FROM testTable";& & & & & & & $result = mysql_query($query) or die (mysql_error());& & & & $row = mysql_fetch_array($result);& & & & foreach ($row as $var =& $key) {& & & & & & $this-&{$var} = $key;& & & & }& & & & }}$table = new testTableData();echo $table-&name;echo $table-&user;echo $table-&date;?&
&?php$he = 'loves';$loves = 'you';$you = 'he';echo $$$he." ".$$$$he." ".$$he;
To generate a family of variables, such as $a1, $a2, $a3, etc., one can use "variable variables" as follows:&?php for ($i = 1; $i &= 5; $i++) {& ${a.$i} = "value";}& & echo "$a1, $a2, $a3, $a4, $a5";?&Note that the correct syntax is ${a.$i} rather than the perhaps more intuitive $a{$i}The dot (.) is the string concatenation operator.A family of variables might be used as an alternative to arrays.
Want to access object's property or array value using variable variables but not possible?Here's a workaround to it:&?phpfunction varvar($str){& & if(strpos($str,'-&') !== false){& & & $parts = explode('-&',$str);& & & & global ${$parts[0]};& & & & return ${$parts[0]}-&$parts[1];& & }elseif(strpos($str,'[') !== false && strpos($str,']') !== false){& & & & $parts = explode('[',$str);& & & & global ${$parts[0]};& & & & $parts[1] = substr($parts[1],0,strlen($parts[1])-1);& & & & return ${$parts[0]}[$parts[1]];& & }else{& & & & global ${$str};& & & & return ${$str};& & }}$arrayTest = array('value0', 'value1', 'test1'=& 'value2', 'test2'=& 'value3');$objectTest = (object)$arrayTest;$test = 'arrayTest[1]';var_dump(varvar($test)); var_dump($$test); $test2 = 'objectTest-&test2';var_dump(varvar($test2)); var_dump($$test2); ?&CheersSam-Mauris Yong
Another Superglobal example:&?phpfunction sgvv() {& & $G =& $_GET;& & $v = 'G';& & var_dump(${$v});& & }?&
&?php$key& & & & = 'post';$type& & && = '_'.strtoupper($key);$copy& & && = ${$type}; $reference& = &${$type}; ?&
A note on Variable variables/functions and classesTo store a function name in a variable and call it later, within a class, you do the following:-&?phpclass test_class{& & var $func='display_UK';& function display_UK()& & {& & & & echo "Hello";& & }& & function display_FR()& & {& & & & echo "Bonjour";& & }& & function display()& & {& & & & $this-&{$this-&func}(); }}$test=new test_class();$test-&display_UK(); $test-&display_FR();$test-&display();?&This allows you to specify the function required. It works better then a big switch statement as it allows for extending the class more easily. (ie adding display_ES(); )
If you need to access one of the superglobals using a variable variable, you can look it up in $GLOBALS:&?PHPdefine('FORM_METHOD', 'post');function getFormVariable( $fieldName, $defaultValue ){& & global $FILTER_METHOD;& & $getpost = $GLOBALS[ '_' . strtoupper(FILTER_METHOD) ];& & if ( ! array_key_exists( $fieldName, $getpost& & ) )& & { return $defaultValue; }& & if ( empty(& & $getpost[ $fieldName ]& & & & & & ) )& & { return $defaultValue; }& & return $getpost[ $fieldName ];}echo "&form method=\"".FORM_METHOD."\"&\n";?&

我要回帖

更多关于 天刀下载礼包 的文章

 

随机推荐