I am new to php and i have seen rather Ambiguous function name convention in php and this confuses me as i regularly forget function names. I suppose i should give you an example.
If function for encoding is htmlentities then why it's opposite is named html_entitiy_decode rather than something like entitiesdecode or the one which is more close to htmlentities.
There are matching function names too but i think php does not have a consistent approach to naming its functions.
Any ideas please as it makes hard for me to remember function names. Thanks
No, PHP doesn't really have a consistent approach to functions names -- that's mainly for two reasons :
Historical reasons : once functions have been released with those names, they can't be changed
Extensions / libraries : PHP is a "glue" language that incorporates several external libraries, and it often used the names of the functions of those libraries -- which are not necessarily consistent.
Fortunately, the PHP community and developpers are aware of that, and try not to repeat this mistake now, when they develop new functions -- but things will most likely remain like this for old functions.
The best you can do is to adopt one naming convention for your classes/functions/methods/variables, and respect it in your projects ; that'll already be a good start.
There is somewhat related question and answer in the PHP FAQ about parameter order:
I cannot remember the parameter order of PHP functions, are they random?
PHP is a glue that brings together hundreds of external libraries, so sometimes this gets messy. However, a simple rule of thumb is as follows:
Array function parameters are ordered as "needle, haystack" whereas String functions are the opposite, so "haystack, needle".
The first sentence of the answer can be applied to function naming as well.
For your own functions, have a look at the Userland Naming Guide and/or consider following one of the Coding Conventions like Zend or PEAR.
I'm afraid that this is a problem with PHP that you're going to have to live with. You could wrap these "misnamed" functions with your own, but that will obviously make calling those functions more expensive.
I would give simple answer, the fact is that it is because of compatibility. A function once given a name can not be reversed as it has been used in thousands of projects and the language core as well as pear and pecl. Thanks
Related
Is it inevitable that all php functions will be used sooner or later when developing applications using php? Should only the required functions be learned to complete a project or should all functions be briefly understood before working on programs using php?
The List:
PHP Function List
Also is there a benefit to learning deprecated functions from previous releases of php besides legacy applications?
I have worked quite a bit developing applications using the .NET framework (c#) and found it extremely helpful to understand mainly how the majority of classes work before undertaking a project. Before that it seemed like I was constantly looking back and forth between coding and documentation, and not that we should'nt be reading the documentation but that it takes the fun out of coding when you can't go a statement without looking at the documentation.
Now I have made basic applications using PHP, and the majority of it has been the way I just described. Can I get your thoughts on how functions in PHP should be approached?
It is impossible to learn all functions available in the PHP standard library. Impossible I say.
There are a few handful of functions you'll need every day, and you'll discover them rather quickly and learn them by heart simply by using them. Beyond that there are hundreds of specialized functions you'll need every once in a while, depending on the project. You'll probably need to look up their specifics whenever you need them. Beyond that there are thousands upon thousands of functions you'll rarely need, if ever. You'll need to be able to find those when the need arises, but not any sooner.
The best way is to keep the manual close at hand and search it whenever you think "there should be a function for that". You'll do this a lot in the beginning and less often later on.
Feel free to skim the manual for function groups, you may discover that there are functions for stuff you didn't even know you could do. That may be valuable knowledge some day. Do not try to memorize everything in detail though. It won't stick anyway and only bore you to tears.
It should be approached as with any other language - you try to code something, get stuck, look up the docs if you find something related to your problem and use that. Otherwise you extend your research. There is no need to learn everything and anything. Personally, I don't see the point of reading about all functions simply to have read of them. Why should I, if I don't need them? Even though this is not coding directly, YAGNI (you ain't gonna need it) applies here as well. Learn about the functions when the need arises, not simply because you can.
IMHO, you should understand what certain function does rather then how it is doing it.. Obviously there are exceptions of functions that are similar (i.e. str_replace vs preg_replace or print vs echo - mostly string functions) and knowing how they work might give you an insight of performance.
Learning ALL php functions is not really necessary as you will not need them in everyday coding. You'll learn as you go (e.g. you need to manipulate and array; then you go and read all PHP array function and see if any suits the need for your problem. rather then doing it another way around. learning all php functions and start coding)
I can only support th answers given...
It is more or less impossible because there are a lot of functions, and when you have learned all the function there are functions you do not know they exist.
You have no big benefit comparing to the time you need to learn them. All important functions you will use every day and so learn them by using them.
Every day there are new libraries, or new versions of existing and useful libraries, every day some other programmer writes a new function and post this function in one of the millions pages on the web.
When you need some special funciton, you will use the manual, or if it is some exotic function use google. And when there are no solution for you problem, you will code som own funcitons and libraries and use them instead of functions in the manual or other libraries...
So I think that are some of plenty reasons not to learn all php functions...
Of course not.
Only string manipulation ones.
Dunno where did you get that list. It's totally useless. Not list but structured reference is what you really need.
Just take a brief tour on manual sections to picture yourself list of PHP features, so, you'll know where to look on occasion.
Only string manipulation functions deserve closer look, just because PHP itself is mainly string manipulation language.
I am using PHP in eclipse. It works ok, I can connect to my remote site, there is colour coding of code elements and some code hints.
I realise this may be too long to answer all questions, if you have a good answer for one part, answering just that is ok.
Firstly General Coding
I have found that it is easy to
loose track of included files and
their variables. For example if
there was a database $cursor it is
difficult to remember or even know
that it was declared in the included
file (this becomes much worse the
more files you include). How are
people dealing with this?
How are people documenting their
code - in particular the required
GET and POST data?
Secondly OO Development:
Should I be going full OO in my
development. Currently I have a
functions library which I can
include and have separated each
"task" into a separate file. It is a
bit nasty but it works.
If I go OO how do I structure the
directories in PHP, java uses
packages - what about php?
How should I name my files, should I
use all lower case with _ for spaces
"hello_world.php"? Should I name
classes with Uppercase like Java
"HelloWorld.php"? Is there a
different naming convention for
Classes and regular function files?
Thirdly Refactoring
I must say this is a real pain. If
I change the name of a variable in
one place I have to go through whole
document and each file that included
this file and change the name their
too. Of course, errors everywhere
is what results. How are people
dealing with this problem? In Java
if you change the name in one place
it changes everywhere.
Are there any plugins to improve php
refactoring? I am using the
official PHP version of Eclipse from
their website.
thanks
Firstly General Coding
1) OO can help you with that. As you encapsulate variables and functionality, they don't go out and mess with the namespaces. Assumind I understand right what problem you hint at, using an OO approach helps alleviating conflicts that can arise when you are inadvertedly redeclaring varables. (Note: Alleviate. Not completely prevent on its own. ;))
Otherwise a practise i have encounterd is prepending variable names with something like a 'package name' -- which merely shifts the problem one level up and isn't exactely beautiful either. :|
2) "However suits their purpose". PHPdoc is a good start; will help to create API documentation.
Secondly OO Development:
3) As said before -- "it depends". Do it when needed. You don't have to go full OO for "hello world". But you can. Weigh the costs and benefits of either route and choose wisely. Though I personally want to suggest when in doubt favour OOP over 'unstructured' approaches. Basically, know your tools and when to use them -- then you can make that call on your own easily. :)
4) As far as I can see, the directories "are structured like packages". Mind you, "directories" and "like". Having said that, various frameworks have solved that problem for theirselves; cf; th eother answers.
5) Again, however you please. There is not a definitive way You Have To Do It Or Else. Just stick to it once you chose your path ;3
Aside of that certain frameworks etc. have their own naming conventions. Symfony, e.g., uses CamelCase like Java.
Thirdly Refactoring
I must say this is a real pain.
yes :3 But it pays off.
If I change the name of a variable in one place I have to go through whole
document and each file that included this file and change the name their too.
Of course, errors everywhere is what results. How are people dealing with
this problem? In Java if you change the name in one place it changes everywhere.
No, it doesn't. If you get yourself a tool with support you only have to use the refactoring tool once; but if you rename a class property in java, there is no magic bot that walks through the internet and automagically makes sure everyone on the planet uses the new name. ;)
But as for how to prevent it -- be smart. Honour program contracts, i.e. use interfaces. Do not use functions / members you shouldn't use directly. Watch the hierarchies. Use a reasonable division of code and respect this division's boundaries.
But how people deal with that problem? Well, search and replace I suppose ;)
As for the Eclipse-Plugin -- The dynamic nature of PHP makes it more difficult to automagically refactor code; we can't always use static type hinting etc., and divination of argument and return types is impossible more often than not. So, to the extent of my knowledge, 'automatic refactoring' is not as well-supported by tools as in the Java world. Though I am sure for the doable cases, there should be plugins. :)
I've found using a PHP framework (e.g. Zend, Cake, CodeIgniter, etc) can force class structures and naming conventions while generally addressing autoloading as well. Using PHPDoc formatting liberally helps with code-completion and hinting as well as documenting specific requirements (e.g. method parameter definitions).
For the OO Development part:
I am using the autoload functionality to load the classes dynamically. My directory structure is like packages in java. My classes are named like in java (e.g. HelloWorld.php). But the class is defined with the complete path to that class (e.g. class FW_package1_package2_HelloWorld {...}).
If a class is called the autoload method replaces all _ against / and searches for the class with the extracted path (e.g. FW/package1/package2/HelloWorld.php).
I am strongly influenced by Java, so that I chose this way.
Take a look at nWire for PHP. It is a plugin for Eclipse PDT which provides code exploration and visualization.
It can easily be used to trace dependencies within your application and it is very handy for OO projects, enabling you to visualize class hierarchies and much more.
It doesn't support refactoring, but it can assist by showing you the references of a given components (e.g. a function or a field).
I'm going to be starting a fairly large PHP application this summer, on which I'll be the sole developer (so I don't have any coding conventions to conform to aside from my own).
PHP 5.3 is a decent language IMO, despite the stupid namespace token. But one thing that has always bothered me about it is the standard library and its lack of a naming convention.
So I'm curious, would it be seriously bad practice to wrap some of the most common standard library functions in my own functions/classes to make the names a little better? I suppose it could also add or modify some functionality in some cases, although at the moment I don't have any examples (I figure I will find ways to make them OO or make them work a little differently while I am working).
If you saw a PHP developer do this, would you think "Man, this is one shoddy developer?"
Additionally, I don't know much (or anything) about if/how PHP is optimized, and I know that usually PHP performace doesn't matter. But would doing something like this have a noticeable impact on the performance of my application?
You might be the only developer now but will someone else ever pick up this code? If so you really should stick mainly to the standard library names if you're doing nothing more than simply wrapping the call.
I've worked with code where the author has wrapped calls like this and it really does harm the ability to quickly understand the code
If you saw a PHP developer do this, would you think "Man, this is one shoddy developer?"
Well no...but I'd think "Damn...I've got to learn this guys new naming standard which although well-intentioned will take me time"
I assume you are referring not only to naming conventions, but also to the merry mixture of function (needle, haystack) and function(haystack, needle) parameter orders.
I can totally understand the desire to build sane wrappers around these in self-defense. I still rather wouldn't do it, though, simply because it adds a proprietary layer to your project that will make it harder to understand for others. Everybody knows what array_push does, but MyArrayFunctions::push one may have to look up, or even look into to find out what it does.
I tend to stick with the standards, even though they're admittedly crappy in this case. Plus, with a decent IDE that can look up functions and parameters as you type, the problem is already much reduced.
On the other hand, I can't really see any harm in, say, a static class Array that brings all the push(), pop(), array_this() and array_that() into one standard form. I'd say it's up to you, really.
Simple wrappers wont hit your performance, but this might confuse any future developers on the project. As a PHP programmer you slowly come to expect the weird naming conventions.
If you are adding any functionality its great to have consistent conventions. I have worked with a PHP static class that did wrap the native array functions (and add new ones). It was quite convenient to always have the same argument placements.
In my opinion OOP implementations of for example an array are okay, you will wrap them and partially modify functionality, however just renaming functions and shuffling arguments I don't like.
If you really need to do it make sure you comment it with phpdoc so people can see the correct syntax in the autocomplete of their IDE.
I have read a lot of popular standards manuals for open source PHP projects.
A lot enforce underscores for variables spaces, and a lot enforce camelCase.
Should global functions and variables be named differently to class methods/properties?
I know the most important thing is consistency, but I'd like to hear some thoughts on this.
What would you recommend?
I find camelCase a little more pleasant to type, because I find the underscore a bit awkward to type.
Don't use global variables.
I avoid procedural coding in PHP, I find OOP is easier to keep things organized. Besides, doesn't PHP have enough stuff in it's global namespace already?
Generally I try to stick to:
Classes are StudlyCaps singular or plural nouns, as appropriate: Item, Row, DB, Items.
Variables are lowercase nouns, singular or plural depending on what they hold: $column, $name
Constants are singular upper-case nouns: DEBUG, TYPE_FOO.
Methods are camelCase, and begin with singular verbs (get, perform, do), followed by a noun (singular or plural) describing what it operates on or returns (getThing(), getThings())
It definitely depends on what you're coding for. If I'm coding PHP or PEAR, I use camelCase. If I'm doing Python/Django, I use under_scores. If I'm writing ELisp, I use dashed-separators.
In PHP itself, almost every native function is underscore separated. Most of the PHP code examples in the documentation are underscore separated.
In most languages I think Camel or Pascal Casing is more appropriate, but I think there's clear history for using underscore separation in PHP.
Zend Frameworks naming convention (Which is based on PEAR) is probably the closest you come to a standard in the PHP world. Personally, I prefer to use lowercase_underscore for variable names, but otherwise I mostly follow ZF's convention.
Update on 10 year anniversary:
These days, there is a standard, which is largely accepted within the community. You should stick with that:
https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md
Yes, the most important thing is consistency. If you are the lone developer, stick with a method. If you are working with a team, talk to the other team members. Differentiating between globals, functions/methods and classes will make reading the code much easier. For some people camelCase is easier than using_underlines so your team needs to discuss the options and pick a style.
Note: I use underscores for my MySQL table_names, I use UpperCamelCase for MySQL field names:
Normally I use $lowerCamelCase for variable names and class properties, but if it contains the value from a field, I use the $UpperCamelCase field name, or if it is an array of data from a table, I'll use the $table_name. This way I can easily grep for SomeField or some_table and find everything referring to it.
You don't have to use this exact system, but being able to search for all references to a field or table is a huge benefit.
I used to prefer to use camelCase, but for the sake of consistency in bigger applications, I have adopted CodeIgniter's style guide.
Even if you don't use their framework, you can appreciate the work that went into defining clear and comprehensive styles: http://codeigniter.com/user_guide/general/styleguide.html
My goal - whatever the specific format of the name - is adding more information. Does the name improve the understanding of the code and/or express something important?
If it does, great, then you've succeeded in it.
If the name doesn't add anything, why did you bother naming it?
I wrote on this one earlier this week:
http://caseysoftware.com/blog/useful-naming-conventions
I would recommend reading the PEAR Coding Standards. Since PEAR is the official PHP Extension and Application Repository, it can be considered the language's official coding standard.
I'm just curious if any project exists that attempts to group all (or most) of PHP's built-in functions into a more object-oriented class hierarchy. For example, grouping all the string functions into a single String class, etc.
I realize this won't actually solve any problems (unless the modifications took place at the PHP source code level), since all the built-in functions would still be accessible in the global namespace, but it would certainly make usability much easier.
Way too many times. As soon as someone discovers that PHP has OO features they want to wrap everything in classes.
The point to the OO stuff in PHP is so that you can architect your solutions in whichever way you want. But wrapping the existing functions in Objects doesn't yield much payoff.
That being said PHP's core is quite object oriented already. Take a look at SPL.
I think something like this is intergral for PHP to move forward. Being mainly a .Net programmer, I find PHP painful to work in with it's 1 million and 1 global functions. It's nice that PHP 5.3 has namespaces, but it doesn't help things much when their own libraries aren't even object oriented, let alone employ namespaces. I don't mind PHP as a language so much, but their API is terribly disorganized, and it probably needs a complete overhaul. Kind of like what VB went through when it became VB.Net.
To Answer your question, Yes there exists several of libraries that do exactly what you are talking about. As far as which one you want to use is an entirely different question. PHPClasses and pear.org are good places to start looking for such libraries.
Update:
As the others have suggested SPL is a good library and wraps many of built in php functions. However there still are lots of php functions that it does not wrap. Leaving us still without a silver bullet.
In using frameworks such as Cakephp and Zend (others too), I have noticed that they attempt to solve some of these problems by including their own libraries and building basics such as DB connectivity into the frame work. So frameworks may be another solution
I don't agree. Object Oriented Programming is not inherently better than procedural programming. I believe that you should not use OO unless you need polymorphic behavior (inheritance, overriding methods, etc). Using objects as simple containers for code is not worth the overhead. This is particularly true of strings because their used so much (e.g. as array keys). Every application can usually benifit from some polymorphic features but usually at a high level. Would you ever want to extend a String class?
Also, a little history is necessary to understand PHP's odd function naming. PHP is grounded around The Standard C Library and POSIX standard and uses many of the same function names (strstr, getcwd, ldap_open, etc). This is actually a good thing because it minimizes the amount of language binding code, ensures that a full well thought out set of features (just about anything you can do in C you can do in PHP) and these system libraries are highly optimized (e.g. strchr is usually inlined which makes it about 10x faster).