Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP constants undefined - but they are defined!

Tags:

php

constants

I'm using constants to set various configuration variables within a script.

The INC_PATH constant is defined within the script that includes the class library.

define('INC_PATH',$_SERVER['DOCUMENT_ROOT'].'includes/');
include('class.lib.php');

The class library contains various include('someClass.php') lines. It also contains:

require(INC_PATH.'DB.class.php');

The class library throws a notice:

Use of undefined constant INC_PATH - assumed 'INC_PATH'

How is the class library not able to see that the INC_PATH constant has been defined? I thought constants were global?

like image 682
bcmcfc Avatar asked Jul 09 '10 11:07

bcmcfc


People also ask

Can you define a constant in PHP?

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name).

What is undefined constant in PHP?

Code Inspection: Undefined constantReports the references to constants that are not found in the project files, configured include paths, or among the PHP predefined constants.

Which of the following is correct about constants in PHP?

Q 3 - Which of the following is correct about constants vs variables in PHP? A - Constants may be defined and accessed anywhere without regard to variable scoping rules.

How do you define constant explain using define () function in PHP?

Constants can be defined using the const keyword, or by using the define()-function. While define() allows a constant to be defined to an arbitrary expression, the const keyword has restrictions as outlined in the next paragraph. Once a constant is defined, it can never be changed or undefined.


1 Answers

Yes, but they must be defined before:

<?php
echo INC_PATH; //undefined
define('INC_PATH', "foo");
echo INC_PATH; //defined

In response to your comment

I can't reproduce that:

a.php

<?php
define('INC_PATH',$_SERVER['DOCUMENT_ROOT']."/");
include('b.php.inc');

b.php.inc

<h1><?php require(INC_PATH . "c.php.inc"); ?></h1>

c.php.inc

<?php echo INC_PATH; ?>

Asking for a.php gives:

<h1>U:/htdocs/</h1>
like image 108
Artefacto Avatar answered Sep 22 '22 02:09

Artefacto