I'm creating a global variable called domain. I have a single site with many different URL's (country based .co.uk, co.ca etc)

I'm also using OOP. Inside some classes are methods which return a URL. How can I use the global domain inside my class without having to pass it in each time?

    Ick. Global variables. Still, that's what the global keyword is for. But consider having a domain class that does URL construction, instead of scattering the task throughout a whole bunch of other classes that are probably doing other things already.

      @Weedpacket got me thinking (as is often the case), and I spent way more time than I should have playing around with this. 🙂 (Probably needs a better class name, as it's not only about the Domain?)

      <?php
      
      class Domain {
        public readonly string $domain;  // PHP 8.1+
      
        public function __construct(string $domain) {
          // maybe add some validation of the string?
          $this->domain = $this->trim($domain);
        }
      
        public function url(string $url): string {
          return 'https://' . $this->domain . '/' . $this->trim($url);
        }
      
        public function url_get(string $url, array $query): string {
          return $this->url($this->trim($url) . '?' . http_build_query($query));
        }
      
        private function trim(string $text): string {
          return trim($text, " \n\r\t\v\x00/"); // added "/" to the usual suspects
        }
      }
      
      // test
      
      $domain = new Domain(' /nog.dog.com/ ');
      echo $domain->url_get('/this/is/a/test.php ', [
        'a' => "Howdy, y'all.",
        'a/b/c' => "That's weird.",
        'nothing' => null
      ]);
      
      // outputs:
      https://nog.dog.com/this/is/a/test.php?a=Howdy%2C+y%27all.&a%2Fb%2Fc=That%27s+weird.

        Global variables are generally discouraged for various reasons. One reason is that it increases the chance of a name collision if you combine your code with other modules or libraries. Global variables also introduce very serious problems if you are writing code that is multithreaded or highly concurrent. Some typical such problems are race conditions and deadlock. Multithreading and/or concurrency in PHP are extremely rare, but you can probably avoid these problems by defining constants when you initialize your program, before you start running any major processes:

        define('MY_DOMAIN', 'example.co.uk');

        You still run the risk of a name collision, though. PHP allows the use of Namespaces to reduce this risk.

        Good programming practice usually involves feeding such values into your functions and constructors:

        // assume this is some configuration file
        $my_config = json_decode('./my-config.json');
        // and you can feed it into your OOP code via constructor or whatever
        $my_object = new myClass($my_config);

        If you still want to define a global variable, you can define $domain at some top level of your code and make it visible within functions by using the global keyword:

        // defined at the top level of your code
        $domain = 'example.co.uk';
        
        function my_func($foo) {
            global $domain;
            echo "foo is $foo\n";
            echo "domain is $domain\n";
        }

        A slightly better approach is to explicitly use the PHP superglobal variable, $GLOBALS:

        $GLOBALS['domain'] = 'example.co.uk';
        
        function my_func($foo) {
            echo "foo is $foo\n";
            echo "domain is {$GLOBALS['domain']}\n";
        
        }

        You can also define constants attached to a class:

        class MyClass
        {
            const CONSTANT = 'example.co.uk';
        
            function showDomain() {
                echo  self::DOMAIN . "\n";
            }
        }
        
        echo MyClass::DOMAIN . "\n";

        I'm not really sure from your post what you're trying to accomplish, but hope this helps.

          4 days later

          You can also use a package like phpdotenv - you'd define the domain in your .env file, then use $_ENV to retrieve them.

            Write a Reply...