0

I'm trying get a value of my array, but return error message:

Undefined variable: titulo_por_permissao in /home/user/scripts/code.php on line 10

Here's my code:

<?php
    $titulo_por_permissao = [
        0 => 'Membro',
        1 => 'Ponto de venda',
        2 => 'Representante',
        5 => 'Administrador'
    ];
    
function pegaTitulo($permissao){
    $result = $titulo_por_permissao[$permissao] ? $titulo_por_permissao[$permissao] : 'Nenhum';
    return $result; 
}
echo pegaTitulo(1);

If i put it this way, it works:

<?php
    $titulo_por_permissao = [
        0 => 'Membro',
        1 => 'Ponto de venda',
        2 => 'Representante',
        5 => 'Administrador'
    ];
    
function pegaTitulo($permissao,$titulo_por_permissao){
    $result = $titulo_por_permissao[$permissao] ? $titulo_por_permissao[$permissao] : 'Nenhum';
    return $result; 
}
echo pegaTitulo(1,$titulo_por_permissao);

What i wnat is declare my var out of function scope and use it in the function without send as an attribute.

Antharaz
  • 33
  • 7
  • 2
    `What i wnat is declare my var out of function scope and use it in the function without send as an attribute.`...why? That's the sort of hideous thing JavaScript lets you do, and it usually causes more problems than it solves. Scope exists for many good reasons, and global variables are usually a maintenance nightmare. But if you _really_ want to, then read https://www.php.net/manual/en/language.variables.scope.php and note the bit about the `global` keyword. – ADyson Jun 07 '22 at 15:01
  • Ty so much, i'll read here now <3 – Antharaz Jun 07 '22 at 15:19

1 Answers1

0

You can achieve it this way. But it is never recommended.

<?php
$titulo_por_permissao = [
        0 => 'Membro',
        1 => 'Ponto de venda',
        2 => 'Representante',
        5 => 'Administrador'
    ];
    
function pegaTitulo($permissao){
    global $titulo_por_permissao; //declare it as global variable
    $result = $titulo_por_permissao[$permissao] ? $titulo_por_permissao[$permissao] : 'Nenhum';
    return $result; 
}
echo pegaTitulo(2);
?>
Nik
  • 352
  • 1
  • 11