Home Backend Development PHP Tutorial 变量的变量,PHP和你_PHP

变量的变量,PHP和你_PHP

Jun 01, 2016 pm 12:35 PM
echo index variable Record this

变量的变量PHP 和 你

在我最近做的一个项目中我发现了一个新的概念关于在PHP中使用变量的变量。在我的程序中我需要在一个页面同时更新多个记录在我经过相当长时间的痛苦思索之后脑海中偶然地闪现出了变量的变量variable variable这一概念所有的困惑就一扫而光了。

介绍

什么叫作变量的变量根据PHP手册变量的变量是指取得一个变量的值并把它作为另一个变量的变量名。这表述显得相当的直接容易和那些在一个句子中使用“变量”这个词弄混淆。给一个简单的例子你定义一个变量 --- x 等于 this --- 然后定义一个变量的变量意味着你把 x 的值作为新变量的名在这个例子中这个新变量的值是 is cake。用PHP来表示如下


$x = "this";
$$x = "is cake";

?>

这个符号$$是在PHP中对变量的变量的表示方法。现在我们可以用两种不同的方式来引用这两个变量 $x 和 $$x 了。


echo "$x ${$x}";

?>


echo "$x $this";

?>

上面两段程序都将输出 this is cake。注意echo语句中$$x被写成${$x}这是让PHP知道你要输出的是变量的变量而不是一个$字符与$x变量。

你是不是仍很迷惑也许吧你想要一些更深入更有用的例子下一节我将向你展示怎样用变量的变量在一个页面编辑多条记录的。


例子

假设你已有一个MySQL数据库保存了对一些感兴趣的站点的链接库中有一个表submissions字段如下

SubmissionID
PostedBy
Link
Description
Approved

现在你想显示在表中所有的已创建但没有被认可的链接这个编辑的页面应可以更正一些输入时的错误并用适当的单选按钮来为每一个记录设置是否允许(Approved)然后一次把更新后的记录都提交到表中。

首先当你从数据库出提取所有的记录并显示出来时你必须为每一个记录设置一个唯一的名字这将让我们在提交时可以循环地辩别出各个记录的值。代码如下


//初始化变量的记数器

$index = 0;
$index_count = 0;

echo "

n"
;
echo "n";
echo"".
"
n";


/*********
假定我们已从数据库中检索出记录到一个数组中 
$myrow = mysql_fetch_array().
下面的 do...while 循环根据名字为每一个$xstr变量分配了一个值并且连接了$index 的值到结尾,以0为开始。
这样,这个循环的第一次时,$SubmissionIDStr 的值就是 SubmissionID0 ,第二次就是 SubmissionID1 ,以此类推。
***********/


do{

$SubmissionIDStr = SubmissionID.$index;
$PostedByStr = PostedBy.$index;
$LinkStr = Link.$index;
$DescriptionStr = Description.$index;
$ApprovedStr = Aprroved.$index;


//这一段将在屏幕上显示值以每行一条记录。

printf("

n",
$SubmissionIDStr, $myrow["SubmissionID"], $PostedByStr, $myrow["PostedBy"], $LinkStr, $myrow["Link"],
$DescriptionStr, $myrow["Description"], $ApprovedStr, $ApprovedStr);


//每个循环记数器加1

$index++;
$index_count++;

}while($myrow = mysql_fetch_array($result));

// 创建一个索引记数器index_count来跟踪所有的记录数

echo"n";

echo"n";

?>

提交以后我们利用$index_count变量再一次循环遍历页面上所有的变量然后分配这些变量给另一些变量这就用到了变量的变量。


//这个循环遍历所有页面上显示的记录

for($index = 0; $index = $counter; $index++) {


/*****
这部分用我们在前面创建的名字设置了新的变量
从0开始,直到$index_count
*****/


$varSubmissionID = 'SubmissionID'.$index;
$varPostedBy = 'PostedBy'.$index;
$varLink = 'Link'.$index;
$varDescription = 'Description'.$index;
$varApproved = 'Approved'.$index;


/******
这是变量的变量部分,把每个值分配给每个新变量的名。
例如,第一次循环时,分配给记录 SubmissionID0 是从前面得来的值,我们用变量的变量来了取到它。
*******/


$SubmissionIDvalue = $$varSubmissionID;
$PostedByvalue = $$varPostedBy;
$Linkvalue = $$varLink;
$Descriptionvalue = $$varDescription;
$Approvedvalue = $$varApproved;


//更新数据库

$sql = "UPDATE submissions SET PostedBy='$PostedByvalue',Link='$Linkvalue',".
"Description='$Descriptionvalue' WHERE SubmissionID=$SubmissionIDvalue'";
$result = mysql_query($sql);


//如果本记录被设置为approved,更新相应的字段 Approved。

if ($Approvedvalue == '-1') {
$sql = "UPDATE submissions SET Approved='-1' WHERE SubmissionID=$SubmissionIDvalue";
$result = mysql_query($sql);
}

}

?>

我希望这有助于你明白这个变量的变量的基本用法并且在你将来的工作中使用它们提供一些思路。变量的变量这一概念最初也是让我头痛的东西但是一旦你知道了它们工作的基本原理时它们就变成了一块美味的比萨饼。如果有什么问题请让我知道吧。
Posted By LinkDescription Approved
YesNo

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What file is index.html? What file is index.html? Feb 19, 2024 pm 01:36 PM

index.html represents the home page file of the web page and is the default page of the website. When a user visits a website, the index.html page is usually loaded first. HTML (HypertextMarkupLanguage) is a markup language used to create web pages, and index.html is also an HTML file. It contains the structure and content of a web page, as well as tags and elements used for formatting and layout. Here is an example index.html code: &lt

Where can I view the records of things I have purchased on Pinduoduo? How to view the records of purchased products? Where can I view the records of things I have purchased on Pinduoduo? How to view the records of purchased products? Mar 12, 2024 pm 07:20 PM

Pinduoduo software provides a lot of good products, you can buy them anytime and anywhere, and the quality of each product is strictly controlled, every product is genuine, and there are many preferential shopping discounts, allowing everyone to shop online Simply can not stop. Enter your mobile phone number to log in online, add multiple delivery addresses and contact information online, and check the latest logistics trends at any time. Product sections of different categories are open, search and swipe up and down to purchase and place orders, and experience convenience without leaving home. With the online shopping service, you can also view all purchase records, including the goods you have purchased, and receive dozens of shopping red envelopes and coupons for free. Now the editor has provided Pinduoduo users with a detailed online way to view purchased product records. method. 1. Open your phone and click on the Pinduoduo icon.

A guide to using Windows 11 and 10 environment variables for profiling A guide to using Windows 11 and 10 environment variables for profiling Nov 01, 2023 pm 08:13 PM

Environment variables are the path to the location (or environment) where applications and programs run. They can be created, edited, managed or deleted by the user and come in handy when managing the behavior of certain processes. Here's how to create a configuration file to manage multiple variables simultaneously without having to edit them individually on Windows. How to use profiles in environment variables Windows 11 and 10 On Windows, there are two sets of environment variables – user variables (apply to the current user) and system variables (apply globally). However, using a tool like PowerToys, you can create a separate configuration file to add new and existing variables and manage them all at once. Here’s how: Step 1: Install PowerToysPowerTo

How to view and manage Linux command history How to view and manage Linux command history Aug 01, 2023 pm 09:17 PM

How to View Command History in Linux In Linux, we use the history command to view the list of all previously executed commands. It has a very simple syntax: history Some options for pairing with the history command include: Option description -c clears the command history for the current session -w writes the command history to a file -r reloads the command history from the history file -n Limit the number of output of recent commands Simply run the history command to see a list of all previously executed commands in a Linux terminal: In addition to viewing command history, you can also manage command history and perform modifications to previously executed commands , reverse search command history or even delete history completely

Strict mode for variables in PHP7: how to reduce potential bugs? Strict mode for variables in PHP7: how to reduce potential bugs? Oct 19, 2023 am 10:01 AM

Strict mode was introduced in PHP7, which can help developers reduce potential errors. This article will explain what strict mode is and how to use strict mode in PHP7 to reduce errors. At the same time, the application of strict mode will be demonstrated through code examples. 1. What is strict mode? Strict mode is a feature in PHP7 that can help developers write more standardized code and reduce some common errors. In strict mode, there will be strict restrictions and detection on variable declaration, type checking, function calling, etc. Pass

How to check call history in iPhone and export it? How to check call history in iPhone and export it? Jul 05, 2023 pm 12:54 PM

Call recording in iPhone is often underestimated and is one of the most critical features of iPhone. With its simplicity, this feature is of vital importance and can provide important insights about the calls made or received on the device. Whether for work purposes or legal proceedings, the ability to access call records can prove invaluable. In simple terms, call history refers to the entries created on your iPhone whenever you make or receive a call. These logs contain key information, including the contact's name (or number if not saved as a contact), timestamp, duration, and call status (dialed, missed, or not answered). They are a concise record of your communication history. Call history includes call history strips stored on your iPhone

How to view your medication log history in the Health app on iPhone How to view your medication log history in the Health app on iPhone Nov 29, 2023 pm 08:46 PM

iPhone lets you add medications to the Health app to track and manage the medications, vitamins and supplements you take every day. You can then log medications you've taken or skipped when you receive a notification on your device. After you log your medications, you can see how often you took or skipped them to help you track your health. In this post, we will guide you to view the log history of selected medications in the Health app on iPhone. A short guide on how to view your medication log history in the Health App: Go to the Health App>Browse>Medications>Medications>Select a Medication>Options&a

What are instance variables in Java What are instance variables in Java Feb 19, 2024 pm 07:55 PM

Instance variables in Java refer to variables defined in the class, not in the method or constructor. Instance variables are also called member variables. Each instance of a class has its own copy of the instance variable. Instance variables are initialized during object creation, and their state is saved and maintained throughout the object's lifetime. Instance variable definitions are usually placed at the top of the class and can be declared with any access modifier, which can be public, private, protected, or the default access modifier. It depends on what we want this to be

See all articles