I wondered why it said “Do not define resource constants” rather than “You cannot define resource constants“. So I decided to try for myself, and as I did I noticed the following behaviour:Only scalar data (boolean, integer, float and string) can be contained in constants. Do not define resource constants.
Code: Select all
<?php
error_reporting(E_ALL);
$file = ‘temp.txt’;
$h = fopen($file,‘wb’);
define( ‘FILE_HANDLE’ , $h );
$write = fwrite(FILE_HANDLE,‘Testing…’);
fclose(FILE_HANDLE);
echo $write; //10
?>Pondering further why the manual would then state that only scalars should be defined as constants and not resources, I went on trying different things, such as defining the resource attained by mysql_connect() as a constant, and using it for queries, etc. and it always worked. So, I decided to bring this up in ##php on IRC and a member named dools told me the reason.
Constants, by definition, are constant, i.e. They cannot be redefined or modified in any way once they are defined. By this very definition, you may use the constant for what it was defined as, but not do anything to it. And therefore, I understood why the manual tells us not to define resource constants, by trying out what dools told me to do…
Code: Select all
<?php
error_reporting(E_ALL);
$file = ‘temp.txt’;
$h = fopen($file,‘rb’);
define( ‘FILE_HANDLE’ , $h );
fclose(FILE_HANDLE);
$read = fread(FILE_HANDLE,10);
echo $read; //Testing...
?>- The manual does say that resource constants should not be defined, however, it would have made things much easier if this was made a strict rule, or if it had at least thrown an error of level E_NOTICE stating that a resource has been defined as a constant. Perhaps this might be considered for future versions.
- The manual also states that:
However, that is not true for the above experiment. is_resource(FILE_HANDLE) returns true and a resource is in no way a scalar value.Constants may only evaluate to scalar values. - Thirdly, I noticed something strange with the behaviour of the file pointer as a constant. Just the mere act of defining the resource constant affects the rest of the script. I tried the following:
And it still read the file correctly! Notice that this time I have used the variable $h for fclose() and fread() instead of the constant, in which case it should have caused the resource to close, but it does not. The constant FILE_HANDLE is not used at all in the script, but just defining it causes this strange behaviour. If I were to remove the line that defined the constant and leave everything else intact, it would throw the error saying that the resource stream used for fread() is invalid.Code: Select all
<?php error_reporting(E_ALL); $file = ‘temp.txt’; $h = fopen($file,‘rb’); define( ‘FILE_HANDLE’ , $h ); fclose($h); $read = fread($h,10); echo $read; //Testing... ?>