How to include a file that defines constants in a class (and its scope)

Say we have the following:

some.class.php

class
{
    public __construct()
    {
        fun_stuff();
    }

}

configuration.inc

const SOMECONST = 1;
const SOMEOTHERCONST = 2;

I want to do something like this:

some.class.php

class
{
    public __construct()
    {
        include_once(configuration.inc);
        fun_stuff();
    }

}

Now it works, but the constant is not defined within the class ( echo some::SOMECONST;), but rather in the global scope ( echo SOMECONST;)

I really really want to have constants in another file, as this makes a lot of sense in my case. Is there a way to declare constants in the scope of a class? I know that it is impossible to use includeseither requiresinside the class definition, so I do not understand.

+4
source share
3 answers

, php. , consts .

0

- .

class myClassConstant {
  const SOMECONST = 1;
  const SOMEOTHERCONST = 2;
}

class myClass extends myClassConstant {

  public function __construct() {
    echo self::SOMECONST . ' + ' . self::SOMEOTHERCONST . ' = 3';
  }
}

$obj = new myClass(); // Output: 1 + 2 = 3

php, .

+5

How about something simple:

class Foo
{
    public $config;

    public __construct($config)
    {
        $this->config = $config;
        fun_stuff();
    }

    public function Bar()
    {
        echo $this->config['baz'];
    }

}

$foo = new Foo(include_once 'config.php');

config.php

<?php
return array('baz' => 'hello earth');

This is not very explicit though. There are no contracts.

+2
source

Source: https://habr.com/ru/post/1626546/


All Articles