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
https://forums.phpfreaks.com/topic/247659-class-constants/
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
https://forums.phpfreaks.com/topic/247659-class-constants/#findComment-1271782
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.