Basic question about constants |
Hi.
I want to define some values as a constant. Normlay it should done in the config>constants.php In my case i want to create the constant a bit later in a library. In the library i do it in this way "define('mynewconstant', $myarray);" So in CI4 i can access all constants from the config file by the name of them without anything else. in Config file is "define('thiscontant', array();" i can access with "print_r(thiscontant)"; The same way doesnt work with my defined constant from the library why it is so?
PHP.net
Using "define('MY_VAR', 'default value')" INSIDE a class definition does not work as expected. You have to use the PHP keyword 'const' and initialize it with a scalar value -- boolean, int, float, string (or array in PHP 5.6+) -- right away. What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
Oh thanks for this, i havent see it.
So i change it to "const" but it failed, too. Error: "syntax error, unexpected token "const" Maybe it is not possible to do it in a function of a class? in the core-class defination, it works but in a function of this class i get this error. class MyClass { private const MY_CONST=my_value; //this works public function my_function($event) { private const MY_CONST_TWO=my_value; //doesnt work - why? public const MY_CONST_TWO=my_value; //doesnt work, too const MY_CONST_TWO=my_value; //doesnt work, too } }
Class constants should be defined at the same level as your properties and methods. Defining them inside methods would definitely result in an error. Also, if you need to access those constants outside of the class where they are defined, you should set the visibility to public, i.e., public const WHAT_EVER. If you just need the constant inside the class, you can have it as private or protected.
|
Welcome Guest, Not a member yet? Register Sign In |