Reputation: 2413
how do I define a constant inside a function
eg.
class {
public test;
function tester{
const test = "abc";
}
}
Upvotes: 3
Views: 2993
Reputation: 382881
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
}
}
Also, you were missing $
in public variable test
Upvotes: 6
Reputation: 56998
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 ::
Upvotes: 4
Reputation: 33833
I think you want a Class Constant
class SomeClass {
const test = "abc";
function tester() {
return;
}
}
Upvotes: 5