博客列表 >[技术博客] 实例演示分支与循环, Switch 的使用方法

[技术博客] 实例演示分支与循环, Switch 的使用方法

P粉912642467
P粉912642467原创
2022年08月11日 14:59:57479浏览

assignment: 0809

分流

  1. $product = ['catagroy' => 'shoe', 'id' => '0001', 'price' => 160];
  2. printf("Catagroy:%s" . ", ID: %s" . ", Price: %s", $product['catagroy'], $product['id'], $product['price']);
  3. function showProduct(string $cata, string $id, int $price): string
  4. {
  5. return "The new product is " . $cata . ", it's ID is " . $id . ", and the price is " . $price;
  6. }
  7. printf(showProduct($product['catagroy'], $product['id'], $product['price']));
  8. echo call_user_func('showProduct', $product['catagroy'], $product['id'], $product['price']);
  9. echo "<hr>";
  10. echo call_user_func_array('showProduct', $product);
  11. echo "<hr>";

使用对象函数

  1. class newProduct
  2. {
  3. public function newShoes(string $brand, string $color)
  4. {
  5. return "The brand new shoes is form " . $brand . ", and the color is " . $color . ".";
  6. }
  7. }
  8. $obj = new newProduct;
  9. $pg6 = ['nike', 'green'];
  10. // echo $obj->newShoes($pg6[0],$pg6[1]);
  11. echo call_user_func_array([$obj, 'newShoes'], $pg6);

流程控制: 分支

  1. $price = 300;
  2. switch (true) {
  3. case $price < 200:
  4. echo "The price is lower than 200";
  5. break;
  6. case $price = 200:
  7. echo "The price is equal to 200";
  8. break;
  9. case $price > 200:
  10. echo "The price is over 200";
  11. break;
  12. default:
  13. echo "The price is invaild";
  14. break;
  15. }
  16. echo "<hr>";

循环

  1. $shoeInStock = ['Kyrie7','KD15','PG6'];
  2. class shoeStore{
  3. public function displayShoes(){
  4. for($i=0;$i<sizeof($GLOBALS["shoeInStock"]);$i++){
  5. echo ($GLOBALS["shoeInStock"])[$i]."<br>";
  6. }
  7. }
  8. }
  9. $obj2 = new shoeStore;
  10. call_user_func_array([$obj2,'displayShoes'],$shoeInStock);

练习foreach

  1. $users = [
  2. 0=>['id'=>5,'name'=>'猪老师', 'gender'=>0, 'score'=>88],
  3. 1=>['id'=>6,'name'=>'张老师', 'gender'=>1,'score'=>68],
  4. 2=>['id'=>7,'name'=>'狗老师','gender'=>1, 'score'=>98],
  5. ];
  6. foreach ($users as $value){
  7. echo '学号:'.$value['id']. ", 姓名:".$value['name'].", 分数:".$value['score'].", 性别:";
  8. if($value['gender']==0){echo "male";}else{echo "female";}
  9. echo "<br>";
  10. }
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议