row248
row248

Reputation: 119

Trouble with constants

I have error "Use of undefined constant PATH_TO_WORDS - assumed 'PATH_TO_WORDS'".

private function changeFileName($fileName, $path) {
    if ( $path == 'db') {
        $path = PATH_TO_FILES_FROM_DB;
    } elseif ( $path == 'file' ) {
        $path = PATH_TO_WORDS; // there error
    } else {
        throw new Exception("Invalid path for file: $path");
    }

    $fileName = preg_replace('!\\s!', '', $fileName);
    $fileName .= Yii::app()->user->id;

    $wholePath = $path . $fileName;

    return $wholePath;
}

And constants:

const PATH_TO_FILES_FROM_DB = 'userFiles/db/';
const PATH_TO_WORDS = 'userFiles/fromFiles/';

Before, i no used constants and all works fine. They have one class.

Upvotes: 0

Views: 64

Answers (3)

Marc B
Marc B

Reputation: 360672

You're using the constants incorrectly, the references should be:

class foo {
    const PATH_TO_FILES_FROM_DB = 'userFiles/db/';

    function bar() {
          $path = self::PATH_TO_FILES_FROM_DB;
                  ^^^^^^----- need this
    }
}

As you're using them, they're not class constants, they're standard define() constants , e.g.

define('PATH_TO_FILES_FROM_DB', 'userFiles/db/');

class Foo {
   function bar:
       $path = PATH_TO_FILES_FROM_DB;
   }
}

Upvotes: 1

bukart
bukart

Reputation: 4906

just define your constants global

define( 'PATH_TO_FILES_FROM_DB', 'userFiles/db/' );
define( 'PATH_TO_WORDS', 'userFiles/fromFiles/' );

or within your class, than you access them via self::CONSTANTNAME

Upvotes: 0

prodigitalson
prodigitalson

Reputation: 60413

It looks like those are class constants not global constants and they must be accessed via the class like:

// anywhere
TheClassname::CONSTANT_NAME

// inside the class or a descendent class only
self::CONSTANT_NAME

If they are supposed to be global constants then you need to use the define() function to define them like:

// definition
define('CONSTANT_NAME', 'thevalue');

// access from anywhere
CONSTANT_NAME;

Upvotes: 3

Related Questions