Home > Software design >  Instantiate specific class object depending on $variable value without using conditions
Instantiate specific class object depending on $variable value without using conditions

Time:10-27

I would want to write the following code without switch, if else or the ternary operator. The code is shown below:

  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;

  }

CodePudding user response:

Here you go... simple. If you want to call another class here, you can set the classes you want to global, then in the functions called below, you can call them from there using global.

Example output: Screen shot

<?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');

CodePudding user response:

You can make the code more concise by returning a new instance of the class by using class name stored in $type. For calling the constructor with different parameters, make use of splat operator by collecting the params in an array.

<?php

function create($type){
    global $customer, $price, $dimensions;
    $className = ucfirst($type);
    $params = [$customer, $price, $dimensions, $type];
    return new $className(...$params);
}

create($type);

CodePudding user response:

  • Related