Ad

PHP Convert String To Variable Not Working

- 1 answer

This is what i'm trying:

class CategoryController extends Controller{
public $productsOrders= [
    1=> 'product_order_number',
    2=> 'product_name',
    3=> 'product_name',
    4=> 'created_at'
];
public $categoriesOrders= [
    1=> 'category_order_number',
    2=> 'category_name',
    3=> 'category_name',
    4=> 'created_at'
];
public $orderDesc = [
    3, 4
];
public static function getOrder($type){
    $orderId=  request()->order;
    $curOrders = ${$type.'Orders'};
    return $curOrders[$orderId ?? 1] ?? $curOrders[1];
}
}

But when i test it using CategoryController::getOrder('products') I get back:

PHP Notice:  Undefined variable: productsOrders in CategoryController

Why is it happening? the scope is public. If i move those inside the function it works...

Ad

Answer

getOrder is a static method and you are trying to access in non-static variable this error happen. also ${$type.'Orders'} is a local function variable it is not a class variable.

try this

class CategoryController extends Controller{
    public static $productsOrders= [
        1=> 'product_order_number',
        2=> 'product_name',
        3=> 'product_name',
        4=> 'created_at'
    ];
    public static $categoriesOrders= [
        1=> 'category_order_number',
        2=> 'category_name',
        3=> 'category_name',
        4=> 'created_at'
    ];
    public $orderDesc = [
         3, 4
    ];
    public static function getOrder($type){
         $orderId=  request()->order;
         $curOrders = self::${$type.'Orders'};
        return $curOrders[$orderId ?? 1] ?? $curOrders[1];
   }
}

now call it

CategoryController::getOrder('products')
Ad
source: stackoverflow.com
Ad