Welcome Guest, Not a member yet? Register   Sign In
Base_url as a default value in a custom Config file
#1

PHP Code:
namespace App\Config;

use 
CodeIgniter\Config\BaseConfig;

class 
MyConfig extends BaseConfig
{
    public $myTargetLink  base_url() . '/path/to/link';



Hello.

I am wondering how I can access the base_url in a Config file.

Doing this give me an error "Constant expression contains invalid operations"

Is getting the base_url() possible as a default value in a Config file?

Thanks for your time.

Max
Reply
#2

I don't know why you have this error. A workaround would be to define your config like this:
PHP Code:
class MyConfig extends BaseConfig
{
    public $myTargetLink '/path/to/link';


Then when you need it use base_url() like this:
PHP Code:
$myConfig config('MyConfig');
echo 
base_url($myConfig->myTargetLink); 
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#3

You can't use dynamic value like `base_url()` in defining properties.

PHP Code:
class MyConfig extends BaseConfig
{
    public $myTargetLink;

    public function __construct()
    {
        parent::__construct();

        $this->myTargetLink base_url() . '/path/to/link';
    }


Reply
#4

(This post was last modified: 10-16-2021, 11:17 PM by John_Betong.)

@sevmusic,
>>> Is getting the base_url() possible as a default value in a Config file?

Perhaps consider defining the CONST in index.php and it will be available throughout the application:

file:  /index.php
PHP Code:
# DYNAMIC PATH ===================================================
  # dynamic BaseUrl - https://forum.codeigniter.com/thread-74649.html  
  if( TRUE || DEFINED('AUTOMATIC_URL_DETECTION') ) :
    $url = (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) 
        && 
        ('on' == $_SERVER['HTTPS']) 
        "https://" 
        "http://") .$_SERVER['HTTP_HOST']
        ;
    $url .= str_replace
    
(
      basename($_SERVER['SCRIPT_NAME']), 
      ''
      $_SERVER['SCRIPT_NAME']
    );
  endif;  
  defined
('BASE_URL') ?: define('BASE_URL'$url); # app/Paths.php, etc
# DYNAMIC PATH =================================================== 
[
file: app/Config/App.php
PHP Code:
  public $baseURL BASE_URL// http://localhost:8080/'; 
Reply
#5

Good suggestions here! I will also add the Registrars are a great way to add dynamic content to Config files.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB