0

I need to use PHP constant in a static variable but I discover today that it's not possible : Is a global PHP CONSTANT available inside of a Class file?

define("TABLE_PREFIX", "TEST_");

class Test {

    private static $sql_query = "select * from ".TABLE_PREFIX."USER";

    public static function show_query1() {
        echo "My first test";
        echo self::$sql_query;
    }

    public static function show_query2() {
        echo "My second test";
        echo self::$sql_query;
    }

}


Test::show_query1();
Test::show_query2();

I don't want to pass the constant as an argument to the static function and I don't want to declare $sql_query in each static function.

What is the best way to to it ?

EDIT : add demo = http://codepad.org/aqzj2TJh

10
  • 1
    You can use the constant just fine. What you cannot do is use an expression like "concatenated"."strings". Commented Jun 25, 2013 at 10:22
  • You found the right answer already, you just misunderstood it. Commented Jun 25, 2013 at 11:17
  • @YogeshSuthar : classic getter and setter only works in object context. I don't want to define a static setter and to call it each time... (if there is another solution) Commented Jun 25, 2013 at 11:21
  • @Jon : You can use the constant just fine => so why do I get this error : "Parse error: syntax error, unexpected '.', expecting ',' or ';' on line 7" (see the demo link I've added) Commented Jun 25, 2013 at 11:25
  • @deceze : Can you explain please ? Commented Jun 25, 2013 at 11:26

1 Answer 1

1

You can do the same with other way.

define("TABLE_PREFIX", "TEST_");
define("TEST_TABLE_QUERY", "select * from ".TABLE_PREFIX."USER");
class Test {

    private static $sql_query = TEST_TABLE_QUERY;

    public static function show_query1() {
        echo "My first test";
        echo self::$sql_query;
   }

    public static function show_query2() {
        echo "My second test";
        echo self::$sql_query;
   }

}

Hope this can help you.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Amit Kumar Sharma, it works but my sql queries are very big and I get word wrap inside them...
In this case you may use %s in the define("TEST_TABLE_QUERY", "select %s TABLE WHERE %s "); And than can use sprinf() in your class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.