Jump to content

Class constants


cs.punk

Recommended Posts

<?php

class constantTest {

const HELLOWORLD = 'maybe not';

function __construct()
{
	echo HELLOWORLD; // Output: HELLOWORLD
	echo constant('HELLOWORLD'); // Output: Warning: constant() [function.constant]: Couldn't find constant HELLOWORLD
	echo  self::HELLOWORLD . "\n"; // Output: maybe not
}
}

$bob = new constantTest();

 

I have read through the manual but as far as I can see all three methods should output the constant rather than just the last one.

Question: Why?

Link to comment
Share on other sites

I believe it is because the first 2 examples you attempted are looking in the global scope for the constant.

 

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.

 

So to reference the HELLOWORLD constant inside your class you should call self:: as your third example shows.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.