我想撰寫以下代碼而不使用 switch、if else 或三元運算子。代碼如下所示:
switch (type){
case 'bed':
function create{
return new Bed($customer, $price, $dimensions );
}
break;
case 'desk':
function create{
return new Desk($customer, $price, $dimensions);
}
break;
case 'chair':
function create{
return new Chair($customer, $price, $dimensions, $type );
}
break;
}
uj5u.com熱心網友回復:
給你...簡單。如果你想在這里呼叫另一個類,你可以設定你想要全域的類,然后在下面呼叫的函式中,你可以使用 global 從那里呼叫它們。
示例輸出: 螢屏截圖
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
class Bed{
function __construct($customer, $price, $dimensions){
echo "Ordered <b>Bed</b> for: <b>$customer</b> at the price of: <b>$price</b> and with the dimensions of: <b>$dimensions</b>";
}
}
class Chair{
function __construct($customer, $price, $dimensions){
echo "Ordered <b>Chair</b> for: <b>$customer</b> at the price of: <b>$price</b> and with the dimensions of: <b>$dimensions</b>";
}
}
class Desk{
function __construct($customer, $price, $dimensions){
echo "Ordered <b>Desk</b> for: <b>$customer</b> at the price of: <b>$price</b> and with the dimensions of: <b>$dimensions</b>";
}
}
class Furniture{
private function bed($customer, $price, $dimensions){
new Bed($customer, $price , $dimensions);
}
private function chair($customer, $price, $dimensions){
new Chair($customer, $price , $dimensions);
}
private function desk($customer, $price, $dimensions){
new Desk($tcustomer, $price , $dimensions);
}
function __construct($type = null, $customer = null, $price = null, $dimensions = null) {
return $this->$type($customer, $price, $dimensions);
}
}
new Furniture('bed','Joes Momma','$1.99','4x5x2');
uj5u.com熱心網友回復:
您可以通過使用存盤在$type. 要呼叫具有不同引數的建構式,請通過將引數收集到陣列中來使用 splat 運算子。
<?php
function create($type){
global $customer, $price, $dimensions;
$className = ucfirst($type);
$params = [$customer, $price, $dimensions, $type];
return new $className(...$params);
}
create($type);
uj5u.com熱心網友回復:
您可以在 if else 陳述句中使用相同的代碼,如下所示。如果 == 不起作用,請嘗試添加 ===
if(type == "bed"){
function create{
return new Bed($customer, $price, $dimensions );
}}
else if(type == "desk"){
function create{
return new Desk($customer, $price, $dimensions);
}}
else if(type == "chair"){
function create{
return new Chair($customer, $price, $dimensions, $type );
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/520033.html
標籤:php条件语句开关语句
上一篇:如何在php回圈中使用jQuery檢索和修改文本框值
下一篇:根據ID將表中的資料提取到輸入框
