Inspired by past topic .
In php, as in any language, there are constructions that for one reason or another have not found wide application, but knowledge of such non-standard techniques can sometimes make your life easier. Today I will talk about one such opportunity. The article is designed for novice programmers and just curious people.
All (I hope) know the remarkable function of
__autoload, the advantages of which are appreciated by those who have switched to php 5. But even earlier, in 4-ke, it was possible to find constructions of the form:
function init ($ cname) {
if (! class_exists ($ cname)) {
require $ cname. '.inc.php' ;
}
}
')
init ( 'myClass' );
$ a = new myClass;
Now you can’t see this, but the opportunity has remained. And it's a sin not to use it.
And the possibility is that
you can declare classes and functions inside other constructs of a language .
Further examples are about functions, but all of the following is true for classes as well.Consider one example. You have a function, the logic of which depends on some complex condition that does not change (
! ) During the script operation. For example, the logic depends on a sample from the database. The classic solution is:
if ( / * severe condition * / ) {
define ( 'MYCONST' , true );
} else {
define ( 'MYCONST' , false );
}
function my_func () {
if (MYCONST) {
// code
} else {
// different code
}
}
We had to introduce an additional constant, and the clever Pinocchio knows that to produce entities is evil. However, knowing the possibility of wrapping ads in the design, you can rewrite this code as follows:
if ( / * severe condition * / ) {
function my_func () {
// code
}
} else {
function my_func () {
// different code
}
}
Agree, it looks nicer? :)
The idea ends there and fantasy begins. Everyone can dream up himself :) I’ll offer another example that uses the fact that
once declared function in php
becomes globally available .
Example:
function a () {
if (! function_exists ( 'b' )) {
function b () {
if (! function_exists ( 'c' )) {
function c () {
return "Three" ;
}
}
return "Two" ;
}
}
return "One" ;
}
echo a ();
echo b ();
echo c ();
It is not difficult to guess that these three functions can only be called
in this order . It may be useful for all sorts of initializations, etc.
Once again I will make a reservation, these constructions are rather exotic and, perhaps, you will never have to use them in practice, but you still need to know about such possibilities of the language. At least for general development;)
PS: All code kindly highlighted
Source Code Highlighter .