Jump to content

PHP code writing format?


greenace92

Recommended Posts

I apologize ahead of time if this post is redundant, please delete if redundant.

 

While searching or results regarding "Programming test questions" I came across a response that basically said "If your code looks bad, you are immediately overlooked."

 

So, when programming PHP, and most web develop languages, how do you indent properly?

 

I use Kate and Gedit... I don't think they auto-indent properly.

What about bracket placement, and spacing between argument lists/ parameters?

 

Thanks for any help

Link to comment
Share on other sites

Great question!  More people should think like you!

 

There are lots of preferences on "how to indent".  So what I'm showing you is just my personal choice.  I believe it gives one an easier view of the code and makes it much quick to browse thru code looking for "blocks" of statements.

 

I indent any block of code that is wrapped in curly braces (  { }).  I indent any single lines that are part of an if else statement.  I indent all function code, again because it is inside those braces.  I indent if statements that are inside other if statements (of course, I try not to nest too many if statements).

 

Below is a sample ( I hope the site shows it accurately) of what my code would look like:

php line
php line
php line
if (condition)
{
     tabbed line
     tabbed line
}
else
    tabbed line
php line
php line
php line
//******************
//******************
function MyFunction()
{
     php line
     php line
     php line
}

( I see that the forum added blank lines between my original input.  Oh, well....)

(note that this code was posted using the proper code tags for this forum ('php' and '/php' wrapped in square brackets)

 

Also it is encouraged to separate your main html code away from your php code.  Too many people think in a straight line as they write a script and begin by beginning the html document before they do any php.  Start your script with the initialization you need (a session_start is always a good start), determine what you need to do in your php, then do it and save any dynamic information to be displayed in php vars and at the end of your processing output the html document in its entirety, including those php vars where the data they contain should be displayed.  Some html may be generated by the php process, such as building a drop-down box or an html table but that should all be in a loop that is producing the data to be contained by them and therefore makes sense.

Edited by ginerjm
Link to comment
Share on other sites

My tastes run to a combination of modern "best practices" and old-school practices that I got used to while learning to code php many, many, many years ago.

namespace Example;
/**
 *	Description.
 *	Further description
 *	@param		string		$varName		Description
 *	@return		void|boolean				Description
 */
class ExampleClass{
/**
 *	@var	string|null		description
 */
	private	$_myVar;
/**
 *	@var	string|null		description
 */
	public $notAGoodIdea;

/**
 *	Description.
 *	Further description
 *	@param		string		$varName		Description
 *	@return		void|boolean				Description
 */
	public function __construct(MyOtherClass $class){
		$this->_myVar = $class;
	}

/**
 *	Description.
 *	Further description
 *	@param		string		$varName		Description
 *	@param		MyOtherClass	$varName
 *	@return		void|boolean				Description
 */
	public function exampleOutput(array $test, \StdClass $class){
		$test['newInput'] = 'This is an input';
		foreach($test as $t){
			$loop = $this->doIt($t, $this->_myVar->aMethod($class));
		}
		return $class;
	}
}

I indent using tabs and keep the opening brace of methods and classes on the same line as the definition statement, and use camel case for method and property definitions. I also still use an underscore on my private variables, a practice ingrained in me during php4 programming. Admittedly, it's gotten me into some trouble as I'm now working mainly with WordPress, and this isn't at all the style they recommend and code to.

 

Also, I tend to think getters and setters are the way to go, so my name for the public variable - while showing the style I would use - might be a bit biased.

 

In my experience, potential employers can and usually will overlook things like opening brace placement, white space within parentheses, and private property naming quirks as long as the code is readable, variable names make logical sense, indenting is logical (as ginerjm mentioned, anything within curly braces should be indented one additional level from the parent code) and consistent, and the code is documented. Unfortunately, this last one is not as important to some as I believe it should be...

Link to comment
Share on other sites

as Maxdd says commenting a much ignored attribute of programmers.  Sometimes when we get deep into a process and develop some code to do some tricky maneuver we lose all sense of it just a couple of months later when we come back to 'tweak' it a bit.  Comments about your thought process when you write something are essential!

 

Unfortunately, I can't agree with Maxdd on his use of camelcase for naming things.  It's bad enough that JS endorses it - there is no reason for you to introduce it in your own code.  A needless distraction in my opinion since it leads to many errors during development where you inadvertently leave out a capital letter which PHP will not catch and WILL give you an error or worse.  IMHO - stick to all lowercase for your vars.  Another of my preferences is to use initial caps on my own function names just to make them stand out.  MyFunctionName() versus myFunctionName() or myfunctionname().

Link to comment
Share on other sites

@ginerjm - this is probably a bit off-topic, but do you typically write OOP or procedural code? I ask only because I find it interesting that you use a leading cap on functions, while I use leading caps for class names only. No big deal, just interested.

Link to comment
Share on other sites

 

 

IMHO - stick to all lowercase for your vars.  Another of my preferences is to use initial caps on my own function names just to make them stand out.

 

I would think that big ugly reserved word "function" would be enough to make them stand out.

function sore_thumb( $bandaid )
{
}
Link to comment
Share on other sites

Maxdd - I rarely use oop.  Small projects, not enough repetition to warrant classes, use includes for standards pieces of code.

 

Hansfore - function does stand out on the function header, but in use that word isn't obvious!  Of course, function names in php are case-insensitive so it doesn't matter but it's just one of my own conventions.

Link to comment
Share on other sites

This is great, I opened up that PSR-1 and PSR-2 link, thanks guys will refer to these posts for future projects and hopefully ingrain them into my own coding process.

ginerjm
 

This is what I took down from your post, I'm not used to placing the initial bracket after one linebreak after the closing parenthesis I do this:

function name() {

}

as maxxd shows

maxxd

I like the commenting style which shows how far the comments go down by the asterisks on the left side

It's weird but I haven't used classes in PHP at all... not sure if that is a bad thing. Why did you write the following:

public $notAGoodIdea;

Ahh man there is a lot here, nice. Will refer back to this thread.

 

Edited by greenace92
Link to comment
Share on other sites

@greenace92 - that's just my own personal preference (and bias, quite honestly). One of the things I like about OOP is the ability to black-box functionality. A class's public property can be changed from anywhere, whereas a private property can only be modified from within it's own class. So, if I write this:

/**
 *    @var    string|null        description
 */
public $myInteger;

/**
 *    class constructor
 */
    public function __construct(){
        $this->myInteger = 2;
    }

/**
 *    yadda yadda
 */
    public function multiplyIt($yourInteger){
        return $yourInteger * $myInteger;
    }

and call

echo $myClass->multiplyIt(4);

I get 8. If I do this, on the other hand

$myClass->myInteger = 'This is a test';
echo $myClass->multiplyIt(4);

I get an error. And if the reassignment of $myInteger happens in a section of code nowhere near the call to multiplyIt(), the actual source of that bug takes forever to track down. However, if $myInteger is private, any attempt to directly reassign it will throw an error at the reassignment attempt, and you know exactly where the bug is. Taking it a step further, if I create a setter method, I can then test the input value and reject or modify it if it's not an integer, thereby avoiding the whole issue.

Link to comment
Share on other sites

 

A class's public property can be changed from anywhere, whereas a private property can only be modified from within it's own class.

 

Oh man... that was a question I was asked. That is a great ability, if you find something wrong you can edit it where you spotted it, as opposed to finding the original source, I think anyway.

 

what are those two leading underscores for in front of construct function name?

 

oh man this-> haha, haven't implemented this in php either, in jQuery and Java

 

Not sure if I am tired or just don't know...

 

How did you pass 4 through multiplyIt if the argument $yourInteger is set to have 2?

 

ahh nevermind, myInteger doesn't change.

Edited by greenace92
Link to comment
Share on other sites

A good starting point are PSR-1 and PSR-2, because they're thought-out and have already been adopted by many projects.

 

+1.

 

I "mostly" follow those standards with only a couple exceptions. But, as Jacques1 states, consistency is key. But, I would definitely try to somewhat follow a common standard. Even if you are the only one that will work on the code it would be worthwhile when requesting help on this forum.

 

And, as others have stated USE COMMENTS.

Link to comment
Share on other sites

A good starting point are PSR-1 and PSR-2, because they're thought-out and have already been adopted by many projects.

Beat me to it.

 

More and more projects seem to be running with this, so in my opinion, you should too. It means that when you cross paths with these other projects, everything is already familiar and natural.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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