php 2

Thanks Tutorial!

<?php

declare(strict_types=1); // 为了严格明确传入参数的类型,可以每个文件前都加上

function func1($name){ // function with parameter
  return "Hello " . $name . "!";
}

echo func1("Alice");

function func2($name = "nothing came in"){ // run with default parameter
  return "Hello " . $name . "!";
}

echo "<br>";
echo func2();

function func3(string $name) { // function with type-hinted parameter // recommanded
  return "Hello " . $name . "!";
}

function func3_1(string $name) : bool { // 明确表示返回值类型的函数
  if (empty($name)) {
    return true;
  }
  else { 
    return false;
  }
}

function func3_2(bool|object $hm2ns) {
  // 明确严格类型模式后,可以这样写允许可能传入的不同类型参数,例如配合 pdo->fetch 使用
}

is_bool(); // 这么判断类型

echo "<br>";
// echo func3(1); // this will cause a TypeError due to strict_types=1
echo "<br>";  

// scope of variables in functions

$globalVar = "Benjamin";

function func4() {
  // return "Hello " . $globalVar . "!"; //!! different from cpp , it cannot access $globalVar directly

  global $globalVar; // need this first

  $result = "Hello " . $globalVar . "!"; // then ok to access from now on

  // cannot unset the global variable access without removing this variable

  global $result; //

  // return $result . $globalVar; // now $globalVar is undefined here

  return $result;
}

echo func4();
echo "<br>";
echo $globalVar; 

function func5() {
  static $count = 0; // static variable inside function

  $count++;

  return $count;
}
// each time func5 is called, $count keeps its value before.
echo "<br>";
echo func5(); // 1 
echo func5(); // 2
echo func5(); // 3
echo "<br>";

define("PI",3.14); // define constant
// no $ before constant name
//use capitial letters for constant names by convention

function func6() {
  return PI; // 常量可以被直接访问
}

$name = "dingFei";
for ($i = 0,$j = 0; $i < strlen($name); $i++){
  echo $name[$i] . " ";
}

echo "<br>";

while ($j < strlen($name)){
  echo $name[$j] . " ";
  $j++;
}

echo "<br>";

$j = 0;
do {
  global $j;
  echo $name[$j] . " ";
  $j++;
} while ($j < strlen($name));
unset($j); // remove global $j

echo "<br>";

$fruits = array("apple", "banana", "cherry");

foreach ($fruits as $fruit){ // 遍历一个数组的简洁写法
  echo $fruit . " ";
  echo "<br>";
}
/*
  for (v: vec){cout<<i<<" ";} // 老朋友
*/ 

$dingFei = [
  "father" => "dingFei",
  "son" => "DXJ",
  "wife" => "for sure not apple",
];// associative array

foreach ($dingFei as $name){ // 只会输出值
  echo $name . " ";
  echo "<br>";
}

foreach ($dingFei as $relation => $name){ // 键和值
  echo $relation . ": " . $name . " ";
  echo "<br>";
}
posted @ 2026-02-15 19:06  hm2ns  阅读(1)  评论(0)    收藏  举报