6

Just a quick questions please, that I can't find the answer to.

If I define a variable like the below example:

DEFINE('THIS_TEST', 'ABC');

What is the scope of this? Could I then use this with in a class/object function:

public function testFunction() {
    echo THIS_TEST;
} 

I have tried this in something similar but am not getting the results I was expecting, although this could be related to other issues.

Any advice would be appreciated.

5
  • What results do you get? Commented Jan 7, 2015 at 2:41
  • i am using it as a EMAIL_FROM for phpmailer (extended), but the email is not being sent. so i wondered if the defined variable was available to the function without injecting it... and a quick google for the scope did not answer my question Commented Jan 7, 2015 at 2:43
  • I'll bet you're probably getting Parse error: syntax error, unexpected T_PUBLIC... right? Remove the "public". Your code checks out without the "public" but threw the error when included. Commented Jan 7, 2015 at 2:44
  • That issue is not caused by this. See this answer for troubleshooting tips. Commented Jan 7, 2015 at 2:44
  • @Fred-ii- sorry, i am being lazy and have not got as far as looking the errors yet as i started to wonder (wanted to learn) the scope of a DEFINE variable first... + i only included an example which includes the "public function..." this is of course wrapped in a class Commented Jan 7, 2015 at 2:45

2 Answers 2

4

You can read about scoping here.

Like superglobals, the scope of a constant is global. You can access constants anywhere in your script without regard to scope. For more information on scope, read the manual section on variable scope.

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

3 Comments

thanks, thats what i was looking for, could not find it for some reason.... its late here
yep, i also ran my own test too, but thought i would ask here as i could not find the details and find it better to know why things work rather than just knowing they do....
Can you define() inside a class? Will it be accessive only via $class_name->CONSTANT_NAME or will it be super global? Also can you conditionally define() inside an If statement?
3

Assuming you actually mean the lowercase define(), this defines a constant (not a variable), which is available globally (with the exception of namespaces):

http://php.net/manual/en/function.define.php

1 Comment

thanks, thats what i was looking for, could not find it for some reason.... probably as my inexperience called it a "defined variable" and not a constant. thanks!

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.