How to echo in a variable of this function?

1

Let's say I want to give echo $ path off the function. How can I do this? It sounds simple but I do not know!

function armazena_constantes (){

    $path               = '/home/axitech/www/dent';
    $path_admin         = '/home/axitech/www/dent/admin/';
    $base_url           = 'http://' . $_SERVER['HTTP_HOST'];
    $base_url_admin     = $base_url . '/admin/';

}
    
asked by anonymous 06.11.2015 / 17:11

2 answers

2

Return $path at the end of your function. Local variables (those declared within the function) are not accessible in other parts of the code.

You can define an associative array with the directories, and pay the desired part by entering an argument in the function

function base_url($selecionado){
    $dir = ['imagem' => '/imagem/', 'js' => '/js/', 'css' => '/css/'];
    return $dir[$selecionado];
}

//chamada:

echo base_url('css');

Another option is to create a file with constants of the most important directories and import it into other files.

cofing.php

<?php
define('ROOT_DIR', dirname(__FILE__));
define('FUNCTIONS_DIR', ROOT_DIR .DIRECTORY_SEPARATOR. 'functions');
define('IMG_DIR', ROOT_DIR .DIRECTORY_SEPARATOR. 'www' .DIRECTORY_SEPARATOR. 'img');
define('CSS_DIR', ROOT_DIR .DIRECTORY_SEPARATOR. 'www' .DIRECTORY_SEPARATOR. 'css');

On other pages, make an include / require for config.php , be careful to set ROOT_DIR in this example from the point that it is at the root of the project.

index.php

<?php
include_once 'config.php';
echo 'Raiz do projeto: '. ROOT_DIR . '<br> imagens: '. IMG_DIR;
<img src="<?php echo IMG_DIR.'/logo.jpg'" />
    
06.11.2015 / 17:15
5

You can transform the way you store the variables.

function armazena_constantes (){
   $array = [];
   $array['path']               = '/home/axitech/www/dent';
   $array['path_admin']         = '/home/axitech/www/dent/admin/';
   $array['base_url']           = 'http://' . $_SERVER['HTTP_HOST'];
   $array['base_url_admin']     = $base_url . '/admin/';
   return $array;
}

To access just use:

$constantes = armazena_constantes();
echo $contantes['path_admin'];

Or you can use per class and set values on object, giving getPathAdmin and etc to retrieve values.

class constantes {
   private $path;
   //..

   public function __construct(){

         $this->path = '/home/axitech/www/dent';
        // ...

   }

   public function getPath(){

        return $this->path;

    }
}


$constantes = new Constantes();

echo $constantes->getPath();

link

    
06.11.2015 / 17:19