3. أساسيات PHP
3.1. مثال أول
فيما يلي برنامج يوضح الميزات الأساسية لـ PHP.
3.1.1. البرنامج (example_01)
<?php
// this is a comment
// variable used without being declared
$nom = "dupont";
// a screen display
print "nom=$nom\n";
// an array with elements of different types
$tableau = array("un", "deux", 3, 4);
// its number of elements
$n = count($tableau);
// a loop
for ($i = 0; $i < $n; $i++)
print "tableau[$i]=$tableau[$i]\n";
// initialize 2 variables with the contents of an array
list($chaine1, $chaine2) = array("chaine1", "chaine2");
// concatenation of the 2 strings
$chaine3 = $chaine1 . $chaine2;
// result display
print "[$chaine1,$chaine2,$chaine3]\n";
// use function
affiche($chaine1);
// the type of a variable can be known
afficheType($n);
afficheType($chaine1);
afficheType($tableau);
// the type of a variable can change at runtime
$n = "a changé";
afficheType($n);
// a function can return a result
$res1 = f1(4);
print "res1=$res1\n";
// a function can return a table of values
list($res1, $res2, $res3) = f2();
print "(res1,res2,res3)=[$res1,$res2,$res3]\n";
// we could have retrieved these values in a table
$t = f2();
for ($i = 0; $i < count($t); $i++)
print "t[$i]=$t[$i]\n";
// testing
for ($i = 0; $i < count($t); $i++)
// displays only channels
if (getType($t[$i]) == "string")
print "t[$i]=$t[$i]\n";
// other tests
for ($i = 0; $i < count($t); $i++){
// displays only integers >10
if (getType($t[$i]) == "integer" and $t[$i] > 10)
print "t[$i]=$t[$i]\n";
}
// a while loop
$t = array(8, 5, 0, -2, 3, 4);
$i = 0;
$somme = 0;
while ($i < count($t) and $t[$i] > 0) {
print "t[$i]=$t[$i]\n";
$somme+=$t[$i]; //$s//$somme=$somme+$t[$i]
$i++; //$i=$i+1
}
print "somme=$somme\n";
// end of program
exit;
//----------------------------------
function affiche($chaine) {
// displays $chaine
print "chaine=$chaine\n";
}
//----------------------------------
function afficheType($variable) {
// displays the type of $variable
print "type[$variable]=" . getType($variable) . "\n";
}
//----------------------------------
function f1($param) {
// adds 10 to $param
return $param + 10;
}
//----------------------------------
function f2() {
// returns 3 values
return array("un", 0, 100);
}
?>
النتائج:
تعليقات
- السطر 5: في PHP، لا يتم إعلان أنواع المتغيرات. المتغيرات لها نوع ديناميكي يمكن أن يتغير بمرور الوقت
- يمثل $name المتغير الذي يحمل المعرف name
- السطر 8: لعرض نص على الشاشة، يمكنك استخدام عبارة print أو عبارة echo
- السطر 11: تُستخدم الكلمة الرئيسية
*array*لتعريف مصفوفة. يمثل المتغير$name[$i]العنصر$iمن مصفوفة$array. - السطر 14: تُرجع الدالة count($tableau) عدد العناصر في المصفوفة $tableau
- السطر 18: يتم وضع السلاسل بين علامتي اقتباس مزدوجتين " أو علامتي اقتباس مفردة '. يتم تقييم المتغيرات $variable داخل علامتي الاقتباس المزدوجتين، ولكن ليس داخل علامتي الاقتباس المفردة.
- السطر 21: تتيح لك دالة list تجميع المتغيرات في قائمة وتعيين قيمة لها من خلال عملية تعيين واحدة. هنا، $string1="string1" و$string2="string2".
- السطر 24: عامل . هو عامل ربط السلاسل.
- السطر 88: الكلمة الرئيسية function تُعرّف دالة. قد تُرجع الدالة قيمًا أو لا تُرجعها باستخدام عبارة return. يمكن للكود المستدعي تجاهل نتائج الدالة أو استردادها. يمكن تعريف الدالة في أي مكان في الكود.
- السطر 90: تُرجع الدالة المُعرَّفة مسبقًا getType($variable) سلسلة تمثل نوع $variable. قد يتغير هذا النوع بمرور الوقت.
- السطر 79: الدالة المحددة مسبقًا exit تنهي البرنامج النصي.
3.2. نطاق المتغير
3.2.1. البرنامج 1 (example_02)
<?php
// variable scope
function f1() {
// we use the global variable $i
$i = &$GLOBALS["i"];
$i++;
$j = 10;
print "f1[i,j]=[$i,$j]\n";
}
function f2() {
// we use the global variable $i
$i = &$GLOBALS["i"];
$i++;
$j = 20;
print "f2[i,j]=[$i,$j]\n";
}
function f3() {
// we use a local variable $i
$i = 4;
$j = 30;
print "f3[i,j]=[$i,$j]\n";
}
// tests
$i = 0;
$j = 0; /// these two variables are known to a function f via the table $GLOBALS
f1();
f2();
f3();
print "test[i,j]=[$i,$j]\n";
?>
النتائج:
تعليقات
- السطران 29–30: تعريف متغيرين، $i و $j، في البرنامج الرئيسي. هذه المتغيرات غير معروفة داخل الدوال. وبالتالي، في السطر 9، المتغير $j في الدالة f1 هو متغير محلي للدالة f1 ويختلف عن المتغير $j في البرنامج الرئيسي. يمكن للدالة الوصول إلى متغير $variable من البرنامج الرئيسي عبر مصفوفة من المتغيرات العالمية تسمى $GLOBALS. في السطر 7، تشير الترميز $GLOBALS["i"] إلى المتغير العام $i في البرنامج الرئيسي. إذا كتبنا
يتم تعيين قيمة المتغير العام $i للمتغير المحلي $i. هذان متغيران مختلفان، ولن يؤدي تعديل المتغير المحلي $i إلى تعديل المتغير العام $i. الرمز
يجعل المتغير المحلي $i له نفس عنوان الذاكرة للمتغير العام $i. وبالتالي، فإن التعامل مع المتغير المحلي $i يعادل التعامل مع المتغير العام $i.
3.2.2. البرنامج 2 (example_03)
<?php
// the scope of a variable is global to code blocks
$i = 0; {
$i = 4;
$i++;
}
print "i=$i\n";
?>
النتائج:
تعليقات
في بعض اللغات، يكون نطاق المتغير المُعرَّف داخل الأقواس المتعرجة محدودًا بهذه الأقواس: ولا يمكن الوصول إليه خارجها. تظهر النتائج أعلاه أن هذا ليس هو الحال في PHP. المتغير $i المُعرَّف في السطر 5 داخل الأقواس المتعرجة هو نفسه المتغير المستخدم في السطرين 4 و8 خارجها.
3.3. المصفوفات
3.3.1. المصفوفات الكلاسيكية أحادية البعد (example_04)
<?php
// classic paintings
// initialization
$tab1 = array(0, 1, 2, 3, 4, 5);
// routes - 1
print "tab1 a " . count($tab1) . " éléments\n";
for ($i = 0; $i < count($tab1); $i++)
print "tab1[$i]=$tab1[$i]\n";
// routes - 2
print "tab1 a " . count($tab1) . " éléments\n";
reset($tab1);
while (list($clé, $valeur) = each($tab1))
print "tab1[$clé]=$valeur\n";
// add elements
$tab1[] = $i++;
$tab1[] = $i++;
// routes - 3
print "tab1 a " . count($tab1) . " éléments\n";
$i = 0;
foreach ($tab1 as $élément) {
print "tab1[$i]=$élément\n";
$i++;
}
// delete last item
array_pop($tab1);
// routes - 4
print "tab1 a " . count($tab1) . " éléments\n";
for ($i = 0; $i < count($tab1); $i++)
print "tab1[$i]=$tab1[$i]\n";
// delete first element
array_shift($tab1);
// routes - 5
print "tab1 a " . count($tab1) . " éléments\n";
for ($i = 0; $i < count($tab1); $i++)
print "tab1[$i]=$tab1[$i]\n";
// addition at end of table
array_push($tab1, -2);
// routes - 6
print "tab1 a " . count($tab1) . " éléments\n";
for ($i = 0; $i < count($tab1); $i++)
print "tab1[$i]=$tab1[$i]\n";
// addition at the beginning of the table
array_unshift($tab1, -1);
// routes - 7
print "tab1 a " . count($tab1) . " éléments\n";
for ($i = 0; $i < count($tab1); $i++)
print "tab1[$i]=$tab1[$i]\n";
?>
النتائج:
تعليقات
يوضح البرنامج أعلاه عمليات معالجة مصفوفة من القيم. هناك طريقتان لكتابة المصفوفات في PHP:
يُطلق على المصفوفة 1 اسم مصفوفة، ويُطلق على المصفوفة 2 اسم قاموس، حيث يُشار إلى العناصر على أنها مفتاح => قيمة. تشير الصيغة $opposites["beautiful"] إلى القيمة المرتبطة بالمفتاح "beautiful". وهنا، تكون تلك القيمة هي السلسلة "ugly". المصفوفة 1 هي ببساطة نوع من القاموس ويمكن كتابتها على النحو التالي:
وبالتالي، يكون لدينا $array[2]="three". في النهاية، لا يوجد سوى القواميس. في حالة المصفوفة الكلاسيكية المكونة من n عنصرًا، تكون المفاتيح هي الأعداد الصحيحة في النطاق [0,n-1].
- السطر 15: تتيح لك الدالة each($array) إجراء تكرار على قاموس. وعند كل استدعاء، تُرجع زوجًا (مفتاح، قيمة) منه.
- السطر 14: تحدد الدالة reset($dictionary) الدالة each على الزوج الأول (مفتاح، قيمة) في القاموس.
- السطر 15: تتوقف حلقة while عندما ترجع الدالة each زوجًا فارغًا في نهاية القاموس.
- السطر 19: تضيف صيغة $array[]=value قيمة العنصر كآخر عنصر في $array.
- السطر 25: يتم تكرار المصفوفة باستخدام foreach. تسمح لك هذه الصيغة بالتكرار عبر قاموس، وبالتالي مصفوفة، باستخدام صيغتين:
تُرجع الصيغة الأولى زوجًا (مفتاح، قيمة) في كل تكرار، بينما تُرجع الصيغة الثانية عنصر القيمة فقط من القاموس.
- السطر 31: تزيل الدالة array_pop($array) العنصر الأخير من $array
- السطر 39: تزيل الدالة array_shift($array) العنصر الأول من $array
- السطر 47: تضيف الدالة array_push($array,value) القيمة كعنصر أخير في $array
- السطر 39: تضيف الدالة array_unshift($array,value) القيمة كأول عنصر في $array
3.3.2. القاموس (example_05)
<?php
// dictionaries
$conjoints = array("Pierre" => "Gisèle", "Paul" => "Virginie", "Jacques" => "Lucette", "Jean" => "");
// routes - 1
print "Nombre d'éléments du dictionnaire : " . count($conjoints) . "\n";
reset($conjoints);
while (list($clé, $valeur) = each($conjoints))
print "conjoints[$clé]=$valeur\n";
// dictionary sorting on key
ksort($conjoints);
// routes - 2
reset($conjoints);
while (list($clé, $valeur) = each($conjoints))
print "conjoints[$clé]=$valeur\n";
// list of dictionary keys
$clés = array_keys($conjoints);
for ($i = 0; $i < count($clés); $i++)
print "clés[$i]=$clés[$i]\n";
// list of dictionary values
$valeurs = array_values($conjoints);
for ($i = 0; $i < count($valeurs); $i++)
print "valeurs[$i]=$valeurs[$i]\n";
// key search
existe($conjoints, "Jacques");
existe($conjoints, "Lucette");
existe($conjoints, "Jean");
// deleting a key-value
unset($conjoints["Jean"]);
print "Nombre d'éléments du dictionnaire : " . count($conjoints) . "\n";
foreach ($conjoints as $clé => $valeur) {
print "conjoints[$clé]=$valeur\n";
}
// end
exit;
function existe($conjoints, $mari) {
// checks whether the key $mari exists in the dictionary $conjoints
if (isset($conjoints[$mari]))
print "La clé [$mari] existe associée à la valeur [$conjoints[$mari]]\n";
else
print "La clé [$mari] n'existe pas\n";
}
?>
النتائج:
تعليقات
ينطبق الكود أعلاه على القاموس كما رأينا سابقًا بالنسبة للمصفوفة البسيطة. سنعلق فقط على الميزات الجديدة:
- السطر 13: تقوم الدالة ksort (فرز المفاتيح) بفرز القاموس حسب الترتيب الطبيعي للمفاتيح.
- السطر 21: تعرض الدالة array_keys($dictionary) قائمة بمفاتيح القاموس في شكل مصفوفة
- السطر 26: تعرض الدالة array_values($dictionary) قائمة قيم القاموس كمصفوفة
- السطر 47: تُرجع الدالة isset($variable) القيمة true إذا تم تعريف المتغير $variable، وإلا تُرجع القيمة false.
- السطر 36: تقوم الدالة unset($variable) بحذف المتغير $variable.
3.3.3. المصفوفات متعددة الأبعاد (example_06)
<?php
// classic multidimensional tables
// initialization
$multi = array(array(0, 1, 2), array(10, 11, 12, 13), array(20, 21, 22, 23, 24));
// route
for ($i1 = 0; $i1 < count($multi); $i1++)
for ($i2 = 0; $i2 < count($multi[$i1]); $i2++)
print "multi[$i1][$i2]=" . $multi[$i1][$i2] . "\n";
// multidimensional dictionaries
// initialization
$multi = array("zéro" => array(0, 1, 2), "un" => array(10, 11, 12, 13), "deux" => array(20, 21, 22, 23, 24));
// route
foreach ($multi as $clé => $valeur)
for ($i2 = 0; $i2 < count($valeur); $i2++)
print "multi[$clé][$i2]=" . $multi[$clé][$i2] . "\n";
?>
النتائج:
تعليقات
- السطر 5: عناصر المصفوفة $multi هي نفسها مصفوفات
- السطر 12: يصبح المصفوفة $multi قاموسًا (مفتاح، قيمة) حيث تكون كل قيمة مصفوفة
3.3.4. الروابط بين السلاسل والمصفوفات (example_07)
<?php
// string to array
$chaine = "1:2:3:4";
$tab = explode(":", $chaine);
// parcours tableau
print "tab a " . count($tab) . " éléments\n";
for ($i = 0; $i < count($tab); $i++)
print "tab[$i]=$tab[$i]\n";
// table to string
$chaine2 = implode(":", $tab);
print "chaine2=$chaine2\n";
// add an empty field
$chaine.=":";
print "chaîne=$chaine\n";
$tab = explode(":", $chaine);
// parcours tableau
print "tab a " . count($tab) . " éléments\n";
for ($i = 0; $i < count($tab); $i++)
print "tab[$i]=$tab[$i]\n"; //// we now have 5 elements, the last being empty
// let's add another empty field
$chaine.=":";
print "chaîne=$chaine\n";
$tab = explode(":", $chaine);
// parcours tableau
print "tab a " . count($tab) . " éléments\n";
for ($i = 0; $i < count($tab); $i++)
print "tab[$i]=$tab[$i]\n"; //// we now have 6 elements, the last two being empty
?>
النتائج:
تعليقات
- السطر 5: تسترد الدالة explode($separator,$string) حقول $string المفصولة بـ $separator. وبالتالي، فإن explode(":",$string) تُرجع عناصر $string المفصولة بالسلسلة ":" كصفيف.
- تقوم الدالة implode($separator,$array) بعملية معاكسة لعملية الدالة explode. فهي تُرجع سلسلة تتكون من عناصر $array مفصولة بـ $separator.
3.4. السلاسل
3.4.1. الصيغة (example_08)
<?php
// string notation
$chaine1 = "un";
$chaine2 = 'un';
print "[$chaine1,$chaine2]\n";
?>
النتائج:
3.4.2. مقارنة (مثال_09)
<?php
// string comparison tests
compare("abcd", "abcd");
compare("", "");
compare("1", "");
exit;
function compare($chaine1, $chaine2) {
// compare string1 and string2
if ($chaine1 == $chaine2)
print "[$chaine1] est égal à [$chaine2]\n";
else
print "[$chaine1] est différent de [$chaine2]\n";
}
?>
النتائج:
3.5. التعبيرات العادية (مثال_10)
<?php
// regular expression in PHP
// retrieve the various fields of a string
// the model: a sequence of numbers surrounded by any characters
// you only want to retrieve the sequence of digits
$modèle = "/(\d+)/";
// the chain is compared with the
compare($modèle, "xyz1234abcd");
compare($modèle, "12 34");
compare($modèle, "abcd");
// the model: a sequence of numbers surrounded by any characters
// we want the sequence of numbers and the fields that follow and precede them
$modèle = "/^(.*?)(\d+)(.*?)$/";
// the chain is compared with the
compare($modèle, "xyz1234abcd");
compare($modèle, "12 34");
compare($modèle, "abcd");
// the template - a date in dd/mm/yy format
$modèle = "/^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/";
compare($modèle, "10/05/97");
compare($modèle, " 04/04/01 ");
compare($modèle, "5/1/01");
// the model - a decimal number
$modèle = "/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*/";
compare($modèle, "187.8");
compare($modèle, "-0.6");
compare($modèle, "4");
compare($modèle, ".6");
compare($modèle, "4.");
compare($modèle, " + 4");
// end
exit;
// --------------------------------------------------------------------------
function compare($modèle, $chaîne) {
// compares the $chaîne string with the $modèle model
// the chain is compared with the model
$correspond = preg_match($modèle, $chaîne, $champs);
// displaying results
print "\nRésultats($modèle,$chaîne)\n";
if ($correspond) {
for ($i = 0; $i < count($champs); $i++)
print "champs[$i]=$champs[$i]\n";
} else
print "La chaîne [$chaîne] ne correspond pas au modèle [$modèle]\n";
}
?>
النتائج:
تعليقات
- السطران 3-4: نستخدم هنا التعبيرات العادية لاستخراج الحقول المختلفة من سلسلة. تسمح لنا التعبيرات العادية بتجاوز قيود دالة implode. المبدأ هو مقارنة سلسلة بسلسلة أخرى تسمى نمطًا باستخدام دالة preg_match:
$correspond = preg_match($modèle, $chaîne, $champs);
تُرجع دالة preg_match قيمة منطقية تشير إلى ما إذا كان النمط موجودًا في السلسلة أم لا. إذا كان موجودًا، فإن $fields[0] تمثل السلسلة الفرعية المطابقة للنمط. علاوة على ذلك، إذا كان النمط يحتوي على أنماط فرعية محاطة بأقواس، فإن $champs[1] هي الجزء من $string المطابق للنمط الفرعي الأول، و$champs[2] هي الجزء من $string المطابق للنمط الفرعي الثاني، وهكذا...
لننظر إلى المثال الأول. يتم تعريف النمط في السطر 8: وهو يشير إلى تسلسل من رقم واحد أو أكثر (+) (\d) موجود في أي مكان في السلسلة. علاوة على ذلك، يحدد النمط نمطًا فرعيًا محاطًا بأقواس.
- السطر 10: تتم مقارنة النمط /(\d+)/ (تسلسل من رقم واحد أو أكثر في أي مكان في السلسلة) بالسلسلة "xyz1234abcd". نرى أن السلسلة الفرعية 1234 تتطابق مع النمط. لذلك، سيكون $fields[0] مساوياً لـ "1234". علاوة على ذلك، يحتوي النمط على أنماط فرعية محاطة بأقواس. سيكون لدينا $champs[1]="1234".
- السطر 11: يتم مقارنة النمط /(\d+)/ بالسلسلة "12 34". نرى أن السلسلتين الفرعيتين 12 و 34 تتطابقان مع النمط. تتوقف المقارنة عند أول سلسلة فرعية تتطابق مع النمط. لذلك، سيكون $champs[0] = 12 و $champs[1] = 12.
- السطر 12: تتم مقارنة النمط /(\d+)/ بالسلسلة "abcd". لم يتم العثور على أي تطابق.
دعونا نوضح الأنماط المستخدمة في بقية الكود:
$modèle = "/^(.*?)(\d+)(.*?)$/";
بداية السلسلة (^)، ثم 0 أو أكثر (*) من الأحرف العشوائية (.)، ثم 1 أو أكثر (+) من الأرقام، ثم مرة أخرى 0 أو أكثر (*) من الأحرف العشوائية (.). يشير النمط (.*) إلى 0 أو أكثر من الأحرف العشوائية. سيتطابق هذا النمط مع أي سلسلة. وبالتالي، لن يتم العثور على النمط /^(.*)(\d+)(.*)$/ أبدًا لأن النمط الفرعي الأول (.*) سيستهلك السلسلة بأكملها. يشير النمط (.*?)(\d+) إلى 0 أو أكثر من الأحرف العشوائية حتى النمط الفرعي التالي (؟)، وهو في هذه الحالة \d+. وبالتالي، لم تعد الأرقام يتم التقاطها بواسطة النمط (.*). وبالتالي، فإن النمط أعلاه يطابق [بداية السلسلة (^)، تسلسل من أي أحرف (.*؟)، تسلسل من رقم واحد أو أكثر (\d+)، تسلسل من أي أحرف (.*؟)، نهاية السلسلة ($)].
$modèle = "/^\s*(\d\d)\/(\d\d)\/(\d\d)\s*$/";
يتطابق مع [بداية السلسلة (^)، رقمان (\d\d)، الحرف / (\/)، رقمان، /، رقمان، تسلسل من صفر أو أكثر من المسافات (\s*)، نهاية السلسلة ($)]
$modèle = "/^\s*([+|-]?)\s*(\d+\.\d*|\.\d+|\d+)\s*/";
[بداية السلسلة (^)، 0 أو أكثر من المسافات (\s*)، علامة + أو - [+|-] تظهر 0 أو 1 مرة (؟)، سلسلة من 0 أو أكثر من المسافات (\s*)، رقم واحد أو أكثر متبوعًا بعلامة عشرية متبوعة بصفر أو أكثر من الأرقام (\d+\.\d*) أو (|) علامة عشرية (\.) متبوعة برقم واحد أو أكثر (\d+) أو (|) رقم واحد أو أكثر (\d+)، سلسلة من 0 أو أكثر من المسافات (\s*)].
3.6. طريقة تمرير معلمات الدالة (مثال_11)
<?php
// parameter step mode
function f(&$i, $j) {
// $i will be obtained by reference
// $j will be obtained by value
$i++;
$j++;
print "f[i,j]=[$i,$j]\n";
}
// ----------------------------------------tests
$i = 0;
$j = 0;
// $i and $j passed by values
f($i, $j);
print "test[i,j]=[$i,$j]\n";
?>
النتائج:
تعليقات
يوضح الكود أعلاه طريقتين لتمرير المعلمات إلى دالة. لننظر إلى المثال التالي:
- السطر 1: يحدد المعلمات الشكلية $a و $b للدالة f. تعالج هذه الدالة هاتين المعلمتين الشكليتين وتُرجع نتيجة.
- السطر 7: يستدعي الدالة f بمتغيرين فعليين $i و $j. يتم تعريف الارتباطات بين المتغيرات الشكلية ($a, $b) والمتغيرات الفعلية ($i, $j) في السطر 7
- &$a: يشير الرمز & إلى أن المعلمة الشكلية $a ستأخذ قيمة عنوان المعلمة الفعلية $i. بعبارة أخرى، $a و $i هما مرجعان لنفس موقع الذاكرة. إن معالجة المعلمة الشكلية $a تعادل معالجة المعلمة الفعلية $i. ويتضح ذلك من خلال تنفيذ الكود. طريقة التمرير هذه مناسبة لمعلمات الإخراج ومجموعات البيانات الكبيرة مثل المصفوفات والقواميس. وتسمى طريقة التمرير هذه بالتمرير بالمرجع.
- $b: ستأخذ المعلمة الشكلية $b قيمة المعلمة الفعلية $j. وهذا هو التمرير بالقيمة. المعلمتان الشكلية والفعلية هما متغيران مختلفان. لا يؤثر التعامل مع المعلمة الشكلية $b على المعلمة الفعلية $j. ويتضح ذلك من خلال تنفيذ الكود. هذا النمط من التمرير مناسب لمعلمات الإدخال.
- لنأخذ دالة swap كمثال، والتي تأخذ متغيرين شكليين $a و $b. تقوم الدالة بتبديل قيم هذين المتغيرين. وبالتالي، أثناء استدعاء swap($i,$j)، يتوقع الكود المستدعي أن يتم تبديل قيم المتغيرين الفعليين. وهذان متغيران للإخراج (يتم تعديلهما). لذلك سنكتب:
3.7. النتائج التي ترجعها الدالة (مثال_12)
<?php
// results rendered by a function
// a function can return several values in an array
list($res1, $res2, $res3) = f1(10);
print "[$res1,$res2,$res3]\n";
$res = f1(10);
for ($i = 0; $i < count($res); $i++)
print "res[$i]=$res[$i]\n";
// a function can render a pseudo-object
$res = f2(10);
print "[$res->res1,$res->res2,$res->res3]\n";
// end
exit;
// function f1
function f1($valeur) {
// returns an array ($valeur+1,$aleur+2,$baleur+3)
return array($valeur + 1, $valeur + 2, $valeur + 3);
}
// function f2
function f2($valeur) {
// renders a pseudo-object ($valeur+1,$aleur+2,$baleur+3)
$res->res1 = $valeur + 1;
;
$res->res2 = $valeur + 2;
$res->res3 = $valeur + 3;
// makes the object
return $res;
}
?>
النتائج
تعليقات
- يوضح البرنامج السابق أن دالة PHP يمكنها إرجاع مجموعة من النتائج بدلاً من نتيجة واحدة، في شكل مصفوفة أو كائن. يتم شرح مفهوم الكائن بمزيد من التفصيل أدناه
- السطور 19–22: تُرجع الدالة f1 قيمًا متعددة في شكل مصفوفة
- الأسطر 25–33: تُرجع الدالة f2 قيمًا متعددة في شكل كائن
3.8. الملفات النصية (example_13)
<?php
// sequential operation of a text file
// this is a set of lines of the form login:pwd:uid:gid:infos:dir:shell
// each line is put into a dictionary in the form login => uid:gid:infos:dir:shell
// set the file name
$INFOS = "infos.txt";
// we open it in creation
if (!$fic = fopen($INFOS, "w")) {
print "Erreur d'ouverture du fichier $INFOS en écriture\n";
exit;
}
// generate arbitrary content
for ($i = 0; $i < 100; $i++)
fputs($fic, "login$i:pwd$i:uid$i:gid$i:infos$i:dir$i:shell$i\n");
// close the file
fclose($fic);
// we use it - fgets keeps the end-of-line marker
// this prevents the retrieval of an empty string when reading a blank line
// we open it in creation
if (!$fic = fopen($INFOS, "r")) {
print "Erreur d'ouverture du fichier $INFOS en lecture\n";
exit;
}
while ($ligne = fgets($fic, 1000)) {
// delete the end-of-line marker if it exists
$ligne = cutNewLineChar($ligne);
// put the line in a table
$infos = explode(":", $ligne);
// retrieve login
$login = array_shift($infos);
// we neglect the pwd
array_shift($infos);
// create a dictionary entry
$dico[$login] = $infos;
}
// close it
fclose($fic);
// using the dictionary
afficheInfos($dico, "login10");
afficheInfos($dico, "X");
// end
exit;
// --------------------------------------------------------------------------
function afficheInfos($dico, $clé) {
// displays the value associated with key in the $dico dictionary if it exists
if (isset($dico[$clé])) {
// value exists - is it a painting?
$valeur = $dico[$clé];
if (is_array($valeur)) {
print "[$clé," . join(":", $valeur) . "]\n";
} else {
// $valeur is not an array
print "[$clé,$valeur]\n";
}
} else {
// $clé is not a key in the $dico dictionary
print "la clé [$clé] n'existe pas\n";
}
}
// --------------------------------------------------------------------------
function cutNewLinechar($ligne) {
// delete the end-of-line mark from $ligne if it exists
$L = strlen($ligne); // // line length
while (substr($ligne, $L - 1, 1) == "\n" or substr($ligne, $L - 1, 1) == "\r") {
$ligne = substr($ligne, 0, $L - 1);
$L--;
}
// end
return($ligne);
}
?>
ملف infos.txt:
login0:pwd0:uid0:gid0:infos0:dir0:shell0
login1:pwd1:uid1:gid1:infos1:dir1:shell1
login2:pwd2:uid2:gid2:infos2:dir2:shell2
...
login98:pwd98:uid98:gid98:infos98:dir98:shell98
login99:pwd99:uid99:gid99:infos99:dir99:shell99
النتائج:
تعليقات
- السطر 11: تفتح الدالة fopen(filename, "w") الملف filename للكتابة (w = كتابة). إذا كان الملف غير موجود، يتم إنشاؤه. وإذا كان موجودًا، يتم مسح محتوياته. وفي حالة فشل الإنشاء، تُرجع الدالة fopen القيمة false. في العبارة if (!$fic = fopen($INFOS, "w")) {…}، هناك عمليتان متتاليتان: 1) $fic=fopen(..) 2) if( ! $fic) {...}
- السطر 18: fputs($fic,$string) يكتب string إلى ملف $fic.
- السطر 20: fclose($fic) يغلق ملف $fic.
- السطر 25: fopen(filename, "r") يفتح ملف filename للقراءة (r=read). إذا فشل الفتح (الملف غير موجود)، فإن fopen ترجع قيمة false.
- السطر 29: fgets($fic,1000) يقرأ السطر التالي من الملف، بحد أقصى 1000 حرف. في العملية while ($line = fgets($fic, 1000)) {…}، هناك عمليتان متتاليتان: 1) $line = fgets(...) 2) while ( ! $line). بعد قراءة الحرف الأخير من الملف، تُرجع الدالة fgets سلسلة فارغة وتتوقف حلقة while.
- السطر 31: تقرأ دالة fgets سطرًا من النص، بما في ذلك حرف السطر الجديد. تزيل دالة cutNewLineChar في الأسطر 70–79 أي حرف سطر جديد.
- السطر 72: تُرجع الدالة strlen($string) عدد الأحرف في $string.
- السطر 73: تُرجع الدالة substr($line, $position, $size) عدد $size من الأحرف من $line، بدءًا من الحرف رقم $position، حيث يكون الحرف الأول هو #0. في أجهزة Windows، يكون علامة نهاية السطر هي "\r\n". وفي أجهزة Unix، تكون السلسلة "\n".
- السطر 35: تزيل الدالة array_shift($array) العنصر الأول من $array وتعيده كنتيجة.
- السطر 37: يتم استخدام الدالة array_shift($array)، ولكن يتم تجاهل نتيجتها
- السطر 57: تُرجع الدالة is_array($variable) القيمة true إذا كان $variable مصفوفة، وإلا تُرجع القيمة false.
- السطر 58: تقوم الدالة join بنفس عمل الدالة implode التي تناولناها سابقًا