Are constants as evil as global variables and singletons? - php

I've heard many times on this forum that using global variable is a dead sin and implementing singleton is a crime.
It just came to my mind that old good constants bear all the features of these dishonored practices: they are globally accessed and no doubt they introduce globallest state ever.
So, the question is: shouldn't we declare a jihad to constants too, and use all the modern things like DI, IoC or other stylish words all the way instead?

Generally speaking yes, avoid constants. They introduce coupling from the consumers to the global scope. That is, the consumers rely on something outside. This is unobvious, e.g.
class Foo
{
public function doSomething()
{
if (ENV === ENV_DEV) {
// do something this way
} else {
// do something that way
}
}
}
Without knowing the internals of doSomething, you will not know there is a dependency on the global scope having that constant. So in addition of making your code somewhat harder to understand, you are also limiting how it can be reused.
The above is also true for constants that have only one value, e.g.
public function log($message)
{
fwrite(LOGFILE, $message);
}
Here the constant would point to a file resource defined somewhere outside as
define('LOGFILE', fopen('/path/to/logfile'));
And this is just as unobvious as using ENV. It's a dependency that requires something outside the class to exist. And I have to know that in order to work with that object. Since the class using this constant hides this detail, I might try to log something without making sure the constant exists and then I'd wonder why it doesn't work. It doesn't even have to be a resource, LOGFILE could simply contain the path as a string. Same result.
Relying on global constants in your consumers will also require you to setup global state in your unit-tests. This is something you generally want to avoid, even if the constants are fixed value, because the point of the unit-test is to test the unit in isolation and having to put the environment into a certain state hinders this.
Moreover, using global constants always poses the threat of constants of different libraries clashing. As a rule of thumb, don't put anything into the global scope. Use namespaces to cluster constants if you have to use them.
However, note that namespaced constants still have the same issues regarding coupling, so do class constants. As long as this coupling is within the same namespace it's less critical, but once you start to couple to constants from various namespaces you are again hampering reuse. For that matter, consider any constants public API.
An alternative to using constants would be to use immutable Value Objects, for instance:
class Environment
{
private $value;
public function __construct($value)
{
$this->assertValueIsAllowedValue($value);
$this->value = $value;
}
public function getValue() {
// …
This way, you can pass around these values to the objects that need them, in addition to making sure the values are valid. Like always, YMMV. This is just an option. A single constant will not make your code unusable, but relying largely on constants will have a detrimental effect, so as a rule of thumb, try to keep them down to a minimum.
On a related side note, you might also be interested in:
Pros and Cons of Interface constants and
PHP global in functions

The primary reason why global variables are considered bad practice is because they can be modified in one part of a system and used in another part, with no direct link between those two pieces of code.
This leads to potential bugs because it is possible to write code that uses a global variable without knowing (or considering) all the places where it is used and ways in which it could be changed. Or vice-versa, write code that makes a change to a global, without realising the impact that change may have in other unrelated parts of your code.
Constants do not share this issue, because they are... well, constant. Once they're defined, they can't be changed, and thus the issued described in the above paragraph cannot occur.
Therefore, they are fine to use globally.
That said, I have seen some poorly written PHP code that uses define to create constants, but declares the constants differently in different circumstances. This is a mis-use of constants: A constant should be an absolutely fixed value; it should only ever be a single value. If you have something that could potentially be different values on different runs through the program, then it shouldn't be defined as a constant. That sort of thing should indeed be a variable, and then should follow the same rules as other variables.
This sort of mis-use can only happen in a scripted language like PHP; it couldn't happen in a compiled language because you can only define a constant once, in one place and to a fixed value.

There's a big difference between a global variable and a global constant.
The main reason a global variable is shunned is because it can be modified by anything at any time. It can introduce all sorts of hidden dependencies on call/execution order, and can result in identical code working sometimes and not others, depending on if and how the global has been changed. Obviously the bad mojo can be ramped-up even more if you're dealing with concurrency or parallelism.
A global constant is (or should be) exactly the same throughout your code at all times. Once your code starts executing, it's guaranteed that every bit of code viewing it will see the same thing every time. That means there's no danger of introducing accidental dependencies. The use of constants can in fact be very good for improving reliability, as it means you don't need to update the value in several locations if you need to change your code. (Never underestimate human error!)
Singletons are a whole other issue. It's an often-abused design pattern which can basically end up as an object oriented version of global variables. In some languages (such as C++), it can also go very wrong if you're not careful of initialisation order. However, it can be a useful pattern on occasion, although there are usually better alternatives (albeit sometimes requiring slightly more work).
EDIT: Just to expand briefly, you mentioned in your question that global constants introduce the "globallest state ever". That's not really accurate, because a global constant is (or should be) fixed in the same way as the source code is fixed. It defines the static nature of the program, whereas "state" is typically understood as a dynamic run-time concept (i.e. the stuff that can change).

Related

Namespace vs global in PHP Functions? [duplicate]

What is the utility of the global keyword?
Are there any reasons to prefer one method to another?
Security?
Performance?
Anything else?
Method 1:
function exempleConcat($str1, $str2)
{
return $str1.$str2;
}
Method 2:
function exempleConcat()
{
global $str1, $str2;
return $str1.$str2;
}
When does it make sense to use global?
For me, it appears to be dangerous... but it may just be a lack of knowledge. I am interested in documented (e.g. with example of code, link to documentation...) technical reasons.
Bounty
This is a nice general question about the topic, I (#Gordon) am offering a bounty to get additional answers. Whether your answer is in agreement with mine or gives a different point of view doesn't matter. Since the global topic comes up every now and then, we could use a good "canonical" answer to link to.
Globals are evil
This is true for the global keyword as well as everything else that reaches from a local scope to the global scope (statics, singletons, registries, constants). You do not want to use them. A function call should not have to rely on anything outside, e.g.
function fn()
{
global $foo; // never ever use that
$a = SOME_CONSTANT // do not use that
$b = Foo::SOME_CONSTANT; // do not use that unless self::
$c = $GLOBALS['foo']; // incl. any other superglobal ($_GET, …)
$d = Foo::bar(); // any static call, incl. Singletons and Registries
}
All of these will make your code depend on the outside. Which means, you have to know the full global state your application is in before you can reliably call any of these. The function cannot exist without that environment.
Using the superglobals might not be an obvious flaw, but if you call your code from a Command Line, you don't have $_GET or $_POST. If your code relies on input from these, you are limiting yourself to a web environment. Just abstract the request into an object and use that instead.
In case of coupling hardcoded classnames (static, constants), your function also cannot exist without that class being available. That's less of an issue when it's classes from the same namespace, but when you start mix from different namespaces, you are creating a tangled mess.
Reuse is severly hampered by all of the above. So is unit-testing.
Also, your function signatures are lying when you couple to the global scope
function fn()
is a liar, because it claims I can call that function without passing anything to it. It is only when I look at the function body that I learn I have to set the environment into a certain state.
If your function requires arguments to run, make them explicit and pass them in:
function fn($arg1, $arg2)
{
// do sth with $arguments
}
clearly conveys from the signature what it requires to be called. It is not dependent on the environment to be in a specific state. You dont have to do
$arg1 = 'foo';
$arg2 = 'bar';
fn();
It's a matter of pulling in (global keyword) vs pushing in (arguments). When you push in/inject dependencies, the function does not rely on the outside anymore. When you do fn(1) you dont have to have a variable holding 1 somewhere outside. But when you pull in global $one inside the function, you couple to the global scope and expect it to have a variable of that defined somewhere. The function is no longer independent then.
Even worse, when you are changing globals inside your function, your code will quickly be completely incomprehensible, because your functions are having sideeffects all over the place.
In lack of a better example, consider
function fn()
{
global $foo;
echo $foo; // side effect: echo'ing
$foo = 'bar'; // side effect: changing
}
And then you do
$foo = 'foo';
fn(); // prints foo
fn(); // prints bar <-- WTF!!
There is no way to see that $foo got changed from these three lines. Why would calling the same function with the same arguments all of a sudden change it's output or change a value in the global state? A function should do X for a defined input Y. Always.
This gets even more severe when using OOP, because OOP is about encapsulation and by reaching out to the global scope, you are breaking encapsulation. All these Singletons and Registries you see in frameworks are code smells that should be removed in favor of Dependency Injection. Decouple your code.
More Resources:
http://c2.com/cgi/wiki?GlobalVariablesAreBad
How is testing the registry pattern or singleton hard in PHP?
Flaw: Brittle Global State & Singletons
static considered harmful
Why Singletons have no use in PHP
SOLID (object-oriented design)
Globals are unavoidable.
It is an old discussion, but I still would like to add some thoughts because I miss them in the above mentioned answers. Those answers simplify what a global is too much and present solutions that are not at all solutions to the problem. The problem is: what is the proper way to deal with a global variable and the use of the keyword global? For that do we first have to examine and describe what a global is.
Take a look at this code of Zend - and please understand that I do not suggest that Zend is badly written:
class DecoratorPluginManager extends AbstractPluginManager
{
/**
* Default set of decorators
*
* #var array
*/
protected $invokableClasses = array(
'htmlcloud' => 'Zend\Tag\Cloud\Decorator\HtmlCloud',
'htmltag' => 'Zend\Tag\Cloud\Decorator\HtmlTag',
'tag' => 'Zend\Tag\Cloud\Decorator\HtmlTag',
);
There are a lot of invisible dependencies here. Those constants are actually classes.
You can also see require_once in some pages of this framework. Require_once is a global dependency, hence creating external dependencies. That is inevitable for a framework. How can you create a class like DecoratorPluginManager without a lot of external code on which it depends? It can not function without a lot of extras. Using the Zend framework, have you ever changed the implementation of an interface? An interface is in fact a global.
Another globally used application is Drupal. They are very concerned about proper design, but just like any big framework, they have a lot of external dependencies. Take a look at the globals in this page:
/**
* #file
* Initiates a browser-based installation of Drupal.
*/
/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd());
/**
* Global flag to indicate that site is in installation mode.
*/
define('MAINTENANCE_MODE', 'install');
// Exit early if running an incompatible PHP version to avoid fatal errors.
if (version_compare(PHP_VERSION, '5.2.4') < 0) {
print 'Your PHP installation is too old. Drupal requires at least PHP 5.2.4. See the system requirements page for more information.';
exit;
}
// Start the installer.
require_once DRUPAL_ROOT . '/includes/install.core.inc';
install_drupal();
Ever written a redirect to the login page? That is changing a global value. (And then are you not saying 'WTF', which I consider as a good reaction to bad documentation of your application.) The problem with globals is not that they are globals, you need them in order to have a meaningful application. The problem is the complexity of the overall application which can make it a nightmare to handle.
Sessions are globals, $_POST is a global, DRUPAL_ROOT is a global, the includes/install.core.inc' is an unmodifiable global. There is big world outside any function that is required in order to let that function do its job.
The answer of Gordon is incorrect, because he overrates the independence of a function and calling a function a liar is oversimplifying the situation. Functions do not lie and when you take a look at his example the function is designed improperly - his example is a bug. (By the way, I agree with this conclusion that one should decouple code.)
The answer of deceze is not really a proper definition of the situation. Functions always function within a wider scope and his example is way too simplistic. We will all agree with him that that function is completely useless, because it returns a constant. That function is anyhow bad design. If you want to show that the practice is bad, please come with a relevant example. Renaming variables throughout an application is no big deal having a good IDE (or a tool). The question is about the scope of the variable, not the difference in scope with the function. There is a proper time for a function to perform its role in the process (that is why it is created in the first place) and at that proper time may it influence the functioning of the application as a whole, hence also working on global variables.
The answer of xzyfer is a statement without argumentation. Globals are just as present in an application if you have procedural functions or OOP design. The next two ways of changing the value of a global are essentially the same:
function xzy($var){
global $z;
$z = $var;
}
function setZ($var){
$this->z = $var;
}
In both instances is the value of $z changed within a specific function. In both ways of programming can you make those changes in a bunch of other places in the code. You could say that using global you could call $z anywhere and change there. Yes, you can. But will you? And when done in inapt places, should it then not be called a bug?
Bob Fanger comments on xzyfer.
Should anyone then just use anything and especially the keyword 'global'? No, but just like any type of design, try to analyze on what it depends and what depends on it. Try to find out when it changes and how it changes. Changing global values should only happen with those variables that can change with every request/response. That is, only to those variables that are belonging to the functional flow of a process, not to its technical implementation. The redirect of an URL to the login page belongs to the functional flow of a process, the implementation class used for an interface to the technical implementation. You can change the latter during the different versions of the application, but should not change those with every request/response.
To further understand when it is a problem working with globals and the keyword global and when not will I introduce the next sentence, which comes from Wim de Bie when writing about blogs:
'Personal yes, private no'. When a function is changing the value of a global variable in sake of its own functioning, then will I call that private use of a global variable and a bug. But when the change of the global variable is made for the proper processing of the application as a whole, like the redirect of the user to the login page, then is that in my opinion possibly good design, not by definition bad and certainly not an anti-pattern.
In retrospect to the answers of Gordon, deceze and xzyfer: they all have 'private yes'(and bugs) as examples. That is why they are opposed to the use of globals. I would do too. They, however, do not come with 'personal yes, private no'-examples like I have done in this answer several times.
The one big reason against global is that it means the function is dependent on another scope. This will get messy very quickly.
$str1 = 'foo';
$str2 = 'bar';
$str3 = exampleConcat();
vs.
$str = exampleConcat('foo', 'bar');
Requiring $str1 and $str2 to be set up in the calling scope for the function to work means you introduce unnecessary dependencies. You can't rename these variables in this scope anymore without renaming them in the function as well, and thereby also in all other scopes you're using this function. This soon devolves into chaos as you're trying to keep track of your variable names.
global is a bad pattern even for including global things such as $db resources. There will come the day when you want to rename $db but can't, because your whole application depends on the name.
Limiting and separating the scope of variables is essential for writing any halfway complex application.
Simply put there is rarely a reason to global and never a good one in modern PHP code IMHO. Especially if you're using PHP 5. And extra specially if you're develop Object Orientated code.
Globals negatively affect maintainability, readability and testability of code. Many uses of global can and should be replaced with Dependency Injection or simply passing the global object as a parameter.
function getCustomer($db, $id) {
$row = $db->fetchRow('SELECT * FROM customer WHERE id = '.$db->quote($id));
return $row;
}
Dont hesitate from using global keyword inside functions in PHP. Especially dont take people who are outlandishly preaching/yelling how globals are 'evil' and whatnot.
Firstly, because what you use totally depends on the situation and problem, and there is NO one solution/way to do anything in coding. Totally leaving aside the fallacy of undefinable, subjective, religious adjectives like 'evil' into the equation.
Case in point :
Wordpress and its ecosystem uses global keyword in their functions. Be the code OOP or not OOP.
And as of now Wordpress is basically 18.9% of internet, and its running the massive megasites/apps of innumerable giants ranging from Reuters to Sony, to NYT, to CNN.
And it does it well.
Usage of global keyword inside functions frees Wordpress from MASSIVE bloat which would happen given its huge ecosystem. Imagine every function was asking/passing any variable that is needed from another plugin, core, and returning. Added with plugin interdependencies, that would end up in a nightmare of variables, or a nightmare of arrays passed as variables. A HELL to track, a hell to debug, a hell to develop. Inanely massive memory footprint due to code bloat and variable bloat too. Harder to write too.
There may be people who come up and criticize Wordpress, its ecosystem, their practices and what goes on around in those parts.
Pointless, since this ecosystem is pretty much 20% of roughly entire internet. Apparently, it DOES work, it does its job and more. Which means its the same for the global keyword.
Another good example is the "iframes are evil" fundamentalism. A decade ago it was heresy to use iframes. And there were thousands of people preaching against them around internet. Then comes facebook, then comes social, now iframes are everywhere from 'like' boxes to authentication, and voila - everyone shut up. There are those who still did not shut up - rightfully or wrongfully. But you know what, life goes on despite such opinions, and even the ones who were preaching against iframes a decade ago are now having to use them to integrate various social apps to their organization's own applications without saying a word.
......
Coder Fundamentalism is something very, very bad. A small percentage among us may be graced with the comfortable job in a solid monolithic company which has enough clout to endure the constant change in information technology and the pressures it brings in regard to competition, time, budget and other considerations, and therefore can practice fundamentalism and strict adherence to perceived 'evils' or 'goods'. Comfortable positions reminiscent of old ages these are, even if the occupiers are young.
For the majority however, the i.t. world is an ever changing world in which they need to be open minded and practical. There is no place for fundamentalism, leave aside outrageous keywords like 'evil' in the front line trenches of information technology.
Just use whatever makes the best sense for the problem AT HAND, with appropriate considerations for near, medium and long term future. Do not shy away from using any feature or approach because it has a rampant ideological animosity against it, among any given coder subset.
They wont do your job. You will. Act according to your circumstances.
It makes no sense to make a concat function using the global keyword.
It's used to access global variables such as a database object.
Example:
function getCustomer($id) {
global $db;
$row = $db->fetchRow('SELECT * FROM customer WHERE id = '.$db->quote($id));
return $row;
}
It can be used as a variation on the Singleton pattern
I think everyone has pretty much expounded on the negative aspects of globals. So I will add the positives as well as instructions for proper use of globals:
The main purpose of globals was to share information between functions. back when
there was nothing like a class, php code consisted of a bunch of functions. Sometimes
you would need to share information between functions. Typically the global was used to
do this with the risk of having data corrupted by making them global.
Now before some happy go lucky simpleton starts a comment about dependency injection I
would like to ask you how the user of a function like example get_post(1) would know
all the dependencies of the function. Also consider that dependencies may differ from
version to version and server to server. The main problem with dependency injection
is dependencies have to be known beforehand. In a situation where this is not possible
or unwanted global variables were the only way to do achieve this goal.
Due to the creation of the class, now common functions can easily be grouped in a class
and share data. Through implementations like Mediators even unrelated objects can share
information. This is no longer necessary.
Another use for globals is for configuration purposes. Mostly at the beginning of a
script before any autoloaders have been loaded, database connections made, etc.
During the loading of resources, globals can be used to configure data (ie which
database to use where library files are located, the url of the server etc). The best
way to do this is by use of the define() function since these values wont change often
and can easily be placed in a configuration file.
The final use for globals is to hold common data (ie CRLF, IMAGE_DIR, IMAGE_DIR_URL),
human readable status flags (ie ITERATOR_IS_RECURSIVE). Here globals are used to store
information that is meant to be used application wide allowing them to be changed and
have those changes appear application wide.
The singleton pattern became popular in php during php4 when each instance of an object
took up memory. The singleton helped to save ram by only allowing one instance of an
object to be created. Before references even dependancy injection would have been a bad
idea.
The new php implementation of objects from PHP 5.4+ takes care of most of these problems
you can safely pass objects around with little to no penalty any more. This is no longer
necessary.
Another use for singletons is the special instance where only one instance of an object
must exist at a time, that instance might exist before / after script execution and
that object is shared between different scripts / servers / languages etc. Here a
singleton pattern solves the solution quite well.
So in conclusion if you are in position 1, 2 or 3 then using a global would be reasonable. However in other situations Method 1 should be used.
Feel free to update any other instances where globals should be used.

PHP - Purpose of Constants?

What, exactly, is the purpose of using constants (in PHP)? I understand how they work, but in which circumstances are they preferable over, say, a global variable? If anything, wouldn't variables be more flexible because they can be placed inside strings?
I've searched the web, but all I've found is definitions--not actual reason for using one or the other. Can anyone help me to understand the benefits of using one over the other?
in which circumstances are they preferable over, say, a global variable?
Constants don't change. Immutable global state would be preferred over its mutable counterpart; in that way, your state is defined in one location and never changes over the course of your script. Barring the use of runkit your code will not be able to change the state in some ways that you didn't expect.
Also, global variables must be declared inside functions by using the global keyword, though technically that declaration, albeit more type-work is better than assumed global I suppose :)
A constant is dependable. It will not change.
Say for example You are writing a class library that others can use.
Say you want to use Pi to 5 decimal places, and forwhatever reason you don't want to make it a private variable with a getter.
So you do
Class Foo {
public $pi = 3.14159;
}
Now some guy who is using your class accidently does
$foo->pi = 4;
Well that will screw everything up.
So instead, you do
const $pi = 3.14159;
Now you know it won't change and won't screw stuff up. Plus developers will know that you have defined it that specific value for a reason.

PHP global in functions

What is the utility of the global keyword?
Are there any reasons to prefer one method to another?
Security?
Performance?
Anything else?
Method 1:
function exempleConcat($str1, $str2)
{
return $str1.$str2;
}
Method 2:
function exempleConcat()
{
global $str1, $str2;
return $str1.$str2;
}
When does it make sense to use global?
For me, it appears to be dangerous... but it may just be a lack of knowledge. I am interested in documented (e.g. with example of code, link to documentation...) technical reasons.
Bounty
This is a nice general question about the topic, I (#Gordon) am offering a bounty to get additional answers. Whether your answer is in agreement with mine or gives a different point of view doesn't matter. Since the global topic comes up every now and then, we could use a good "canonical" answer to link to.
Globals are evil
This is true for the global keyword as well as everything else that reaches from a local scope to the global scope (statics, singletons, registries, constants). You do not want to use them. A function call should not have to rely on anything outside, e.g.
function fn()
{
global $foo; // never ever use that
$a = SOME_CONSTANT // do not use that
$b = Foo::SOME_CONSTANT; // do not use that unless self::
$c = $GLOBALS['foo']; // incl. any other superglobal ($_GET, …)
$d = Foo::bar(); // any static call, incl. Singletons and Registries
}
All of these will make your code depend on the outside. Which means, you have to know the full global state your application is in before you can reliably call any of these. The function cannot exist without that environment.
Using the superglobals might not be an obvious flaw, but if you call your code from a Command Line, you don't have $_GET or $_POST. If your code relies on input from these, you are limiting yourself to a web environment. Just abstract the request into an object and use that instead.
In case of coupling hardcoded classnames (static, constants), your function also cannot exist without that class being available. That's less of an issue when it's classes from the same namespace, but when you start mix from different namespaces, you are creating a tangled mess.
Reuse is severly hampered by all of the above. So is unit-testing.
Also, your function signatures are lying when you couple to the global scope
function fn()
is a liar, because it claims I can call that function without passing anything to it. It is only when I look at the function body that I learn I have to set the environment into a certain state.
If your function requires arguments to run, make them explicit and pass them in:
function fn($arg1, $arg2)
{
// do sth with $arguments
}
clearly conveys from the signature what it requires to be called. It is not dependent on the environment to be in a specific state. You dont have to do
$arg1 = 'foo';
$arg2 = 'bar';
fn();
It's a matter of pulling in (global keyword) vs pushing in (arguments). When you push in/inject dependencies, the function does not rely on the outside anymore. When you do fn(1) you dont have to have a variable holding 1 somewhere outside. But when you pull in global $one inside the function, you couple to the global scope and expect it to have a variable of that defined somewhere. The function is no longer independent then.
Even worse, when you are changing globals inside your function, your code will quickly be completely incomprehensible, because your functions are having sideeffects all over the place.
In lack of a better example, consider
function fn()
{
global $foo;
echo $foo; // side effect: echo'ing
$foo = 'bar'; // side effect: changing
}
And then you do
$foo = 'foo';
fn(); // prints foo
fn(); // prints bar <-- WTF!!
There is no way to see that $foo got changed from these three lines. Why would calling the same function with the same arguments all of a sudden change it's output or change a value in the global state? A function should do X for a defined input Y. Always.
This gets even more severe when using OOP, because OOP is about encapsulation and by reaching out to the global scope, you are breaking encapsulation. All these Singletons and Registries you see in frameworks are code smells that should be removed in favor of Dependency Injection. Decouple your code.
More Resources:
http://c2.com/cgi/wiki?GlobalVariablesAreBad
How is testing the registry pattern or singleton hard in PHP?
Flaw: Brittle Global State & Singletons
static considered harmful
Why Singletons have no use in PHP
SOLID (object-oriented design)
Globals are unavoidable.
It is an old discussion, but I still would like to add some thoughts because I miss them in the above mentioned answers. Those answers simplify what a global is too much and present solutions that are not at all solutions to the problem. The problem is: what is the proper way to deal with a global variable and the use of the keyword global? For that do we first have to examine and describe what a global is.
Take a look at this code of Zend - and please understand that I do not suggest that Zend is badly written:
class DecoratorPluginManager extends AbstractPluginManager
{
/**
* Default set of decorators
*
* #var array
*/
protected $invokableClasses = array(
'htmlcloud' => 'Zend\Tag\Cloud\Decorator\HtmlCloud',
'htmltag' => 'Zend\Tag\Cloud\Decorator\HtmlTag',
'tag' => 'Zend\Tag\Cloud\Decorator\HtmlTag',
);
There are a lot of invisible dependencies here. Those constants are actually classes.
You can also see require_once in some pages of this framework. Require_once is a global dependency, hence creating external dependencies. That is inevitable for a framework. How can you create a class like DecoratorPluginManager without a lot of external code on which it depends? It can not function without a lot of extras. Using the Zend framework, have you ever changed the implementation of an interface? An interface is in fact a global.
Another globally used application is Drupal. They are very concerned about proper design, but just like any big framework, they have a lot of external dependencies. Take a look at the globals in this page:
/**
* #file
* Initiates a browser-based installation of Drupal.
*/
/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd());
/**
* Global flag to indicate that site is in installation mode.
*/
define('MAINTENANCE_MODE', 'install');
// Exit early if running an incompatible PHP version to avoid fatal errors.
if (version_compare(PHP_VERSION, '5.2.4') < 0) {
print 'Your PHP installation is too old. Drupal requires at least PHP 5.2.4. See the system requirements page for more information.';
exit;
}
// Start the installer.
require_once DRUPAL_ROOT . '/includes/install.core.inc';
install_drupal();
Ever written a redirect to the login page? That is changing a global value. (And then are you not saying 'WTF', which I consider as a good reaction to bad documentation of your application.) The problem with globals is not that they are globals, you need them in order to have a meaningful application. The problem is the complexity of the overall application which can make it a nightmare to handle.
Sessions are globals, $_POST is a global, DRUPAL_ROOT is a global, the includes/install.core.inc' is an unmodifiable global. There is big world outside any function that is required in order to let that function do its job.
The answer of Gordon is incorrect, because he overrates the independence of a function and calling a function a liar is oversimplifying the situation. Functions do not lie and when you take a look at his example the function is designed improperly - his example is a bug. (By the way, I agree with this conclusion that one should decouple code.)
The answer of deceze is not really a proper definition of the situation. Functions always function within a wider scope and his example is way too simplistic. We will all agree with him that that function is completely useless, because it returns a constant. That function is anyhow bad design. If you want to show that the practice is bad, please come with a relevant example. Renaming variables throughout an application is no big deal having a good IDE (or a tool). The question is about the scope of the variable, not the difference in scope with the function. There is a proper time for a function to perform its role in the process (that is why it is created in the first place) and at that proper time may it influence the functioning of the application as a whole, hence also working on global variables.
The answer of xzyfer is a statement without argumentation. Globals are just as present in an application if you have procedural functions or OOP design. The next two ways of changing the value of a global are essentially the same:
function xzy($var){
global $z;
$z = $var;
}
function setZ($var){
$this->z = $var;
}
In both instances is the value of $z changed within a specific function. In both ways of programming can you make those changes in a bunch of other places in the code. You could say that using global you could call $z anywhere and change there. Yes, you can. But will you? And when done in inapt places, should it then not be called a bug?
Bob Fanger comments on xzyfer.
Should anyone then just use anything and especially the keyword 'global'? No, but just like any type of design, try to analyze on what it depends and what depends on it. Try to find out when it changes and how it changes. Changing global values should only happen with those variables that can change with every request/response. That is, only to those variables that are belonging to the functional flow of a process, not to its technical implementation. The redirect of an URL to the login page belongs to the functional flow of a process, the implementation class used for an interface to the technical implementation. You can change the latter during the different versions of the application, but should not change those with every request/response.
To further understand when it is a problem working with globals and the keyword global and when not will I introduce the next sentence, which comes from Wim de Bie when writing about blogs:
'Personal yes, private no'. When a function is changing the value of a global variable in sake of its own functioning, then will I call that private use of a global variable and a bug. But when the change of the global variable is made for the proper processing of the application as a whole, like the redirect of the user to the login page, then is that in my opinion possibly good design, not by definition bad and certainly not an anti-pattern.
In retrospect to the answers of Gordon, deceze and xzyfer: they all have 'private yes'(and bugs) as examples. That is why they are opposed to the use of globals. I would do too. They, however, do not come with 'personal yes, private no'-examples like I have done in this answer several times.
The one big reason against global is that it means the function is dependent on another scope. This will get messy very quickly.
$str1 = 'foo';
$str2 = 'bar';
$str3 = exampleConcat();
vs.
$str = exampleConcat('foo', 'bar');
Requiring $str1 and $str2 to be set up in the calling scope for the function to work means you introduce unnecessary dependencies. You can't rename these variables in this scope anymore without renaming them in the function as well, and thereby also in all other scopes you're using this function. This soon devolves into chaos as you're trying to keep track of your variable names.
global is a bad pattern even for including global things such as $db resources. There will come the day when you want to rename $db but can't, because your whole application depends on the name.
Limiting and separating the scope of variables is essential for writing any halfway complex application.
Simply put there is rarely a reason to global and never a good one in modern PHP code IMHO. Especially if you're using PHP 5. And extra specially if you're develop Object Orientated code.
Globals negatively affect maintainability, readability and testability of code. Many uses of global can and should be replaced with Dependency Injection or simply passing the global object as a parameter.
function getCustomer($db, $id) {
$row = $db->fetchRow('SELECT * FROM customer WHERE id = '.$db->quote($id));
return $row;
}
Dont hesitate from using global keyword inside functions in PHP. Especially dont take people who are outlandishly preaching/yelling how globals are 'evil' and whatnot.
Firstly, because what you use totally depends on the situation and problem, and there is NO one solution/way to do anything in coding. Totally leaving aside the fallacy of undefinable, subjective, religious adjectives like 'evil' into the equation.
Case in point :
Wordpress and its ecosystem uses global keyword in their functions. Be the code OOP or not OOP.
And as of now Wordpress is basically 18.9% of internet, and its running the massive megasites/apps of innumerable giants ranging from Reuters to Sony, to NYT, to CNN.
And it does it well.
Usage of global keyword inside functions frees Wordpress from MASSIVE bloat which would happen given its huge ecosystem. Imagine every function was asking/passing any variable that is needed from another plugin, core, and returning. Added with plugin interdependencies, that would end up in a nightmare of variables, or a nightmare of arrays passed as variables. A HELL to track, a hell to debug, a hell to develop. Inanely massive memory footprint due to code bloat and variable bloat too. Harder to write too.
There may be people who come up and criticize Wordpress, its ecosystem, their practices and what goes on around in those parts.
Pointless, since this ecosystem is pretty much 20% of roughly entire internet. Apparently, it DOES work, it does its job and more. Which means its the same for the global keyword.
Another good example is the "iframes are evil" fundamentalism. A decade ago it was heresy to use iframes. And there were thousands of people preaching against them around internet. Then comes facebook, then comes social, now iframes are everywhere from 'like' boxes to authentication, and voila - everyone shut up. There are those who still did not shut up - rightfully or wrongfully. But you know what, life goes on despite such opinions, and even the ones who were preaching against iframes a decade ago are now having to use them to integrate various social apps to their organization's own applications without saying a word.
......
Coder Fundamentalism is something very, very bad. A small percentage among us may be graced with the comfortable job in a solid monolithic company which has enough clout to endure the constant change in information technology and the pressures it brings in regard to competition, time, budget and other considerations, and therefore can practice fundamentalism and strict adherence to perceived 'evils' or 'goods'. Comfortable positions reminiscent of old ages these are, even if the occupiers are young.
For the majority however, the i.t. world is an ever changing world in which they need to be open minded and practical. There is no place for fundamentalism, leave aside outrageous keywords like 'evil' in the front line trenches of information technology.
Just use whatever makes the best sense for the problem AT HAND, with appropriate considerations for near, medium and long term future. Do not shy away from using any feature or approach because it has a rampant ideological animosity against it, among any given coder subset.
They wont do your job. You will. Act according to your circumstances.
It makes no sense to make a concat function using the global keyword.
It's used to access global variables such as a database object.
Example:
function getCustomer($id) {
global $db;
$row = $db->fetchRow('SELECT * FROM customer WHERE id = '.$db->quote($id));
return $row;
}
It can be used as a variation on the Singleton pattern
I think everyone has pretty much expounded on the negative aspects of globals. So I will add the positives as well as instructions for proper use of globals:
The main purpose of globals was to share information between functions. back when
there was nothing like a class, php code consisted of a bunch of functions. Sometimes
you would need to share information between functions. Typically the global was used to
do this with the risk of having data corrupted by making them global.
Now before some happy go lucky simpleton starts a comment about dependency injection I
would like to ask you how the user of a function like example get_post(1) would know
all the dependencies of the function. Also consider that dependencies may differ from
version to version and server to server. The main problem with dependency injection
is dependencies have to be known beforehand. In a situation where this is not possible
or unwanted global variables were the only way to do achieve this goal.
Due to the creation of the class, now common functions can easily be grouped in a class
and share data. Through implementations like Mediators even unrelated objects can share
information. This is no longer necessary.
Another use for globals is for configuration purposes. Mostly at the beginning of a
script before any autoloaders have been loaded, database connections made, etc.
During the loading of resources, globals can be used to configure data (ie which
database to use where library files are located, the url of the server etc). The best
way to do this is by use of the define() function since these values wont change often
and can easily be placed in a configuration file.
The final use for globals is to hold common data (ie CRLF, IMAGE_DIR, IMAGE_DIR_URL),
human readable status flags (ie ITERATOR_IS_RECURSIVE). Here globals are used to store
information that is meant to be used application wide allowing them to be changed and
have those changes appear application wide.
The singleton pattern became popular in php during php4 when each instance of an object
took up memory. The singleton helped to save ram by only allowing one instance of an
object to be created. Before references even dependancy injection would have been a bad
idea.
The new php implementation of objects from PHP 5.4+ takes care of most of these problems
you can safely pass objects around with little to no penalty any more. This is no longer
necessary.
Another use for singletons is the special instance where only one instance of an object
must exist at a time, that instance might exist before / after script execution and
that object is shared between different scripts / servers / languages etc. Here a
singleton pattern solves the solution quite well.
So in conclusion if you are in position 1, 2 or 3 then using a global would be reasonable. However in other situations Method 1 should be used.
Feel free to update any other instances where globals should be used.

PHP - What are constants, are they good practice, and how do they differ from variables?

Beginner question...
How different is define("$a",365); from $a = 365;?
Thanks!
JDelage
If you define constant define("YEAR",365); you can't change it during execution time so YEAR will always be 365 no meter what. On the other hand variables can change their value during script execution also they have local scope, which means they are available just in the function file they are declared. Constants have global scope they can be accessed from all over the script.
http://php.net/manual/en/language.constants.php
http://planetozh.com/blog/2006/06/php-variables-vs-constants/
Constants are meant to be used for values that do not change during program runtime. They are not stored in memory.
Good practice is to put static parameters that might be changed later in constants at the top of the file, so that they could be found and easily changed, if necessary, instead of find/replacing everything.
Another one: constant should always be in CAPITAL_LETTERS, so it would be clear that it is a constant.
You define constants when you want a globally accessible value that never changes. For example, you might define a constant for website editor- something that has to appear on a lot of pages and would be a severe PITA to change if your company hired a different website editor.
So,
define('WEBEDITOR','Tom Jones');
then whereever you need to output 'Tom Jones', just echo WEBEDITOR.
A variable, is just that: variable. It changes.
A constant has a value that cannot change.
Named constants are usually considered bad practice in most languages (except in the case of compilation conditionals -- which PHP doesn't use, being interpreted -- or if it is assured they are centrally located, such as in config files) so it's best not to overuse them and, instead, look into using class constants where possible.
The reason for this is that it can make it more difficult to determine where a constant has been defined and makes it harder to avoid name clashes.

PHP coding standards at work: Insane, or am I?

I prefer coding standards to be logical. This is my argument for why the following set of standards are not.
I need to know one of two things: (1) why I'm wrong, or (2) how to convince my team to change them.
camelCase: Functions, class names, methods, and variables must be camelCase.
Makes it hard to differentiate between variables and classes
Goes against PHP's lowercase/underscored variables/functions and UpperCamelCase classes
Example:
$customerServiceBillingInstance = new customerServiceBillingInstance(); // theirs
$customer_service_billing_instance = new CustomerServiceBillingInstance();
Functions/methods must always return a value (and returned values must always be stored).
This appears on hundreds of our php pages:
$equipmentList = new equipmentList();
$success = $equipmentList->loadFromDatabase(true, '');
$success = $equipmentList->setCustomerList();
$success = $equipmentList->setServerList();
$success = $equipmentList->setObjectList();
$success = $equipmentList->setOwnerList();
$success = $equipmentList->setAccessList();
The return value is rarely used but always stored. It encourages the use of copy-and-paste.
No static methods
Lines like the following appear thousands of times in the codebase:
$equipmentList = new equipmentList();
$success = $equipmentList->loadFromDatabase();
I would prefer:
$equipmentList = equipmentList::load();
What reason is there to not use static methods or properties? Aren't static methods responsible for non-instance-specific logic? Like initializing or populating a new instance?
Your code is not OOP unless everything returns an object
There's a piece of code that performs a query, checks it several ways for errors, and then processes the resulting array. It is repeated (copied+pasted) several times, so I put it in the base class. Then I was told returning an array is not OOP.
How do you defend these practices? I really do need to know. I feel like I'm taking crazy pills.
If you can't defend them, how do you convince the adamant author they need to be changed?
I would suggest trying to list down the goals of your coding standards, and weigh them down depending on which goals is the most important and which goals are less important.
PS: I don't speak PHP, so some of these arguments may contain blatantly incorrect PHP code.
camelCase: Functions, class names, methods, and variables must be camelCase.
Workplace's Apparent Reason: "consistency" at the cost of "information density in name".
Argument:
1) Since 'new' keyword should always be followed by a class, then you can easily spot illegal instantiation, e.g.:
$value = new functionName();
$value = new local_variable();
$value = new GLOBAL_VARIABLE();
would raise an alarm, because 'new' should be followed by a TitleCase name.
$value = new MyClass(); // correct
Relying on Case makes it easy to spot these errors.
3) Only functions can be called, you can never call variables. By relying on Case Rule, then we can easily spot fishy function calls like:
$value = $inst->ClassName();
$value = $inst->instance_variable();
$value = $GLOBAL_VARIABLE();
3) Assigning to a function name and global variables is a huge deal, since they often lead to behavior that is difficult to follow. That's why any statement that looks like:
$GLOBAL = $value;
$someFunction = $anotherFunction;
should be heavily scrutinized. Using Case Rule, it is easy to spot these potential problem lines.
While the exact Case Rule may vary, it is a good idea to have different Case Rule for each different type of names.
Functions/methods must always return a value (and returned values must always be stored).
Workplace's Apparent Reason: apparently another rule born out of blind consistency. The advantage is that every line of code that isn't a flow control (e.g. looping, conditionals) is an assignment.
Argument:
1) Mandatory assignment makes unnecessary long lines, which harms readability since it increases the amount of irrelevant information on screen.
2) Code is slightly slower as every function call will involve two unnecessary operation: value return and assignment.
Better Convention:
Learn from functional programming paradigm. Make a distinction between "subroutine" and "functions". A subroutine does all of its works by side-effect and does not return a value, and therefore its return value never need to be stored anywhere (subroutine should not return error code; use exception if it is really necessary). A function must not have any side-effect, and therefore its return value must be used immediately (either for further calculations or stored somewhere). By having side-effect free function policy, it is a waste of processor cycle to call a function and ignoring its return value; and the line can therefore be removed.
So, there is three type of correct calls:
mySubroutine(arg); // subroutine, no need to check return value
$v = myFunction(arg); // return value is stored
if (myFunction(arg)) { ... } // return value used immediately
you should never have, for example:
$v = mySubroutine(arg); // subroutine should never have a return value!
myFunction(arg); // there is no point calling side-effect free function and ignoring its return value
and they should raise warning. You can even create a naming rule to differentiate between subroutine and functions to make it even easier to spot these errors.
Specifically disallow having a "functiroutine" monster that have both a side-effect and return value.
No static methods
Workplace Apparent Reason: probably someone read somewhere that static is evil, and followed blindly without really doing any critical evaluation of its advantages and disadvantages
Better Convention:
Static methods should be stateless (no modifying global state). Static methods should be a function, not subroutine since it is easier to test a side-effect-free function than to test the side-effects of a subroutine. Static method should be small (~4 lines max) and should be self-contained (i.e. should not call too many other static methods too deeply). Most static methods should live in the Utility class; notable exceptions to this is Class Factories. Exceptions to this convention is allowed, but should be heavily scrutinized beforehand.
Your code is not OOP unless everything returns an object
Workplace Apparent Reason: flawed understanding of what is OOP.
Argument:
Fundamental datatypes is conceptually also an object even if a language's fundamental datatype doesn't inherit from their Object class.
If you can't defend them, how do you
convince the adamant author they need
to be changed?
By giving strong/valid arguments! Still I think you should only change them when your arguments are really strong! Because most of the programmers at work are used to these coding standards which is a big point why to use them.
==
Like others told before this is pretty subjective, but these are mine opinions/arguments.
1. camelCase: Functions, class names, methods, and variables must be camelCase.
I would use the PHP style if I code in PHP and the Camelcase style if I code in Java. But it does not matter which style you choose as long as you stay consistent.
2. Functions/methods must always return a value (and returned values must always be stored).
This is nonsense in my opinion. In almost all programming languages you have some sort of 'void' type. But from a testing point of view most of the times it is useful if your function are side effect free. I don't agree that your production code should always use the return value especially if it does not have any use.
3. No static methods
I would advice you to read static methods are death to testability from misko
During the instantiation I wire the
dependencies with mocks/friendlies
which replace the real dependencies.
With procedural programing there is
nothing to “wire” since there are no
objects, the code and data are
separate.
Although PHP is a dynamic language so it is not really a big problem. Still the latest PHP does support typing so that I still think most of times static methods are bad.
4. Your code is not OOP unless everything returns an object
I believe(not 100% sure) a truly OOP language should do this(return an object), but I don't agree with this like a of like languages like for example Java(which I believe is not trully OOP). A lot of the times your methods should just return primitives like String/Int/Array/etc. When you are copying and pasting a lot of code it should be a sign that something is not totally right with your design. You should refactor it(but first have a tests(TDD) ready so that you don't break any code).
Many of these coding standards are very subjective, but some important things to consider are:
Get a single set of code naming and style rules, and follow them. If you don't have already defined rules, make sure to get rules figured out. Then work at refactoring the code to follow them. This is an important step in order to make it easier for new developers to jump on board, and keep the coding consistent among developers.
It takes time and effort to change the coding standards your company puts in place. Any change to the rules means that the code really has to be gone through again to update everything to be consistent with the new standards.
Keeping the above in mind, and looking more along the lines of specific PHP coding standards. The first thing to look at is if your company uses any sort of framework, look at the coding standards for that framework as you may want to stick with those in order to stay consistent across all the code. I have listed links to a couple of the popular PHP frameworks below:
Zend Framework Naming Conventions and Zend Framework Code Style
Pear Code Standards
My personal preference in regards to your specific coding styles:
1. camelCase: Functions, class names, methods, and variables must be camelCase
Class names should be Pascal Case (Upper Camel Case).
So in your example:
class CustomerServiceBillingInstance
{
// Your class code here
}
Variables and functions I generally feel should be camel case.
So either one of these, depending on your preference in terms of underscores:
$customerServiceBillingInstance = whatever;
$customer_service_billing_instance = whatever;
2. Functions/methods must always return a value (and returned values must always be stored).
This one seems like extra code and like you could end up using extra resources. If a function doesn't need to return anything, don't return anything. Likewise, if you do not care about what a function returns, don't store it. There is no point in using the extra memory to store something you are never going to look at.
An interesting thing you may want to try on this one, is running some benchmarks. See if it takes extra time to return something and store it even though you are not looking at it.
3. Your code is not OOP unless everything returns an object
In this instance, I feel you have to draw the line somewhere. Performance wise, it is faster for you to do:
return false;
Than to do:
return new Boolean(false); // This would use up unnecessary resources but not add very much to readability or maintainability in my opinion.
Defending a coding standard
To defend a coding standard that you feel is right (or showing why another is not as good), you really are going to have to bring up one of two points.
Performance. If you can show that a particular coding standard is adversely affecting performance, you may want to consider switching.
Maintainability/Readability. Your code should be easy to read/understand.
The goal is to find the happy median between performance and the maintainability/readability. Sometimes it is an easy decision because the most maintainable option is also the best performing, other times there is a harder choice to be made.
Standards and conventions exist for many reasons, but most of these reasons boil down to "they make code easier to write and maintain." Instead of asking "is this the correct way to do X?" just cut right to the chase and ask if this criterion is met. The last point in particular is simply a matter of definition. OOP is a means, not an end.
Many of those are matters of taste. You can argue for or against camelCase all day.
However, the storing of return values that are never used is Wrong. There is no value to the code. The code is not executed. You might as well sprinkle $foo = 47 * 3; around the code.
Any code that is not doing something useful must be removed.
The bigger issue is, if you're working for a clueless manager, it may be time to move.
The one aspect of this that I don't see anybody else commenting on is the "2. Functions/methods must always return a value (and returned values must always be stored)."
If you're not using exceptions, then any function that can fail does have to return a value. The last clause is misworded; return values don't always need to be STORED, but they do always need to be CHECKED. Again, that's IF you're not using exceptions, which isn't common these days, but it's still worth mentioning.
As far as I know quite a few of the conventions you posted are encouraged by the Zend PHP Framework as well. You're not alone, I'm a Codeigniter user and my work is pretty big on using Zend Framework. These kind of naming conventions are absolutely ridiculous and I honestly can only see an advantage of using camelCase for variable names, not function names as it makes things confusing.
Read this: http://framework.zend.com/manual/en/coding-standard.naming-conventions.html
Do these coding conventions look familiar to you?

Categories