3

how do I define a constant inside a function

eg.

class {

     public test;

     function tester{

      const test = "abc";

     }

  }
Charles
  • 50,943
  • 13
  • 104
  • 142
Jeremy Gwa
  • 2,333
  • 7
  • 25
  • 31
  • Just pointing out that you should not be defining a constant inside a function, anyway. That should probably be a property of the object, not a constant of the class, since constants should never have the opportunity to change. – Matchu May 03 '10 at 04:23

4 Answers4

6

You are doing fine but you need to put the const at the class level not inside the function eg:

class {
 const TEST = "abc"; 
 public $test2;

 function tester{
  // code here
 }
}

More info here.

Also, you were missing $ in public variable test

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
5

I think you want a Class Constant

class SomeClass {

  const test = "abc";

  function tester() {
    return; 
  }

}
artlung
  • 33,305
  • 16
  • 69
  • 121
4

By definition, you shouldn't be assigning a value to a constant after its definiton. In the class context you use the const keyword and self:: to access it through the class internally.

class TestClass
{
    const test = "abc";

    function tester()
    {
        return self::test;
    }
}

$testClass = new TestClass();
//abcabc
echo $testClass->tester();
echo TestClass::test;

You can see that you can also access the constant as a static class property using ::

typeoneerror
  • 55,990
  • 32
  • 132
  • 223
3

http://www.php.net/manual/en/language.oop5.constants.php

Anthony
  • 12,177
  • 9
  • 69
  • 105