0

I have one file which is constants inside this file i have one array i want to call that array key into another file,can you please help me to fix the issue..?

constants.php

<?php


namespace App\Ship\Constants;


class Constants
{
    const USER_DEPT = 'MECH';
    const STAFF_DEPT = 'Batch_1';
    const USER_SECTION = 1;
    const STAFF_SECTION =50;

    
    const USER_TYPES = [
            self::USER_DEPT => self::USER_SECTION,
            self::STAFF_DEPT => self::STAFF_SECTION
    ];
}

Controller.php

//$field is either USER or STAFF based on request it's coming
public function check($field){ 
            constants::USER_TYPES[$field.'_DEPT'];
}

Error undefined index USER_DEPT

usersuser
  • 167
  • 12
  • 1
    Where is ```self::SECTION``` declaration? It shows ```Fatal error: Uncaught Error: Undefined constant self::SECTION``` – Anisur Rahman Feb 09 '22 at 08:39
  • 1
    Does this answer your question? [Dynamic constant name in PHP](https://stackoverflow.com/questions/3995197/dynamic-constant-name-in-php) – M. Eriksson Feb 09 '22 at 08:42
  • 1
    When using the above duplicate, don't forget to add `Constants::` for the dynamic constant as well: `Constants::USER_TYPE[constant('Constants::' . $field . '_DEPT')]` – M. Eriksson Feb 09 '22 at 08:43
  • @M.Eriksson, i tried this one but it's throwing an error like `constant(): Couldn't find constant constants::USER_DEPT` – usersuser Feb 09 '22 at 08:52
  • That was just me missing the last `S` in `USER_TYPES`. It should be: `Constants::USER_TYPES[constant('Constants::' . $field . '_DEPT')]`Demo: https://3v4l.org/ccbWs – M. Eriksson Feb 09 '22 at 09:25

1 Answers1

1

When you declare an array key as variable then the actual key will be the assigned by the value of that variable. in your case USER_TYPES array contain these data:

Array
(
    [MECH] => 1
    [Batch_1] => 50
)

Thats why you getting undefined index error

if want to access array index like USER_DEPT then you have to assign your constant like this:

const USER_DEPT = 'USER_DEPT';
const STAFF_DEPT = 'STAFF_DEPT';

Or change array key like:

const USER_TYPES = [
    'USER_DEPT' => self::USER_SECTION,
    'STAFF_DEPT' => self::STAFF_SECTION
];
Anisur Rahman
  • 644
  • 1
  • 4
  • 17