PHP Syntax Formatting
Page 1 of 6 123 ... LastLast
Results 1 to 15 of 85

Thread: PHP Syntax Formatting

  1. #1
    Senior Member iceomnia's Avatar
    Join Date
    Oct 2007
    Posts
    181

    resolved [RESOLVED] Correctly Spacing Out Your Code (To make it easily readable)

    Hi everyone,

    Throughout this website (and others), I have noticed people posting code in an absolute mess.

    I have searched this site for a thread like this, and couldn't find one.

    So therefore i have devised a quick example of good ways to space your code using tabs, in order to make it more readable.

    I believe that people will get a much better response to their questions if they format their code to be more readable, like so:

    An example of how to correctly space out a function:

    PHP Code:
    // Correctly spacing a function with tabs to make it readable.
    function foo($bar)
    {
        
    // Use a coment to tell us what the block below is doing.
        
    if ($bar == true)
        {
            
    $something true;
        }
        
        return 
    $somthing;

    An example of a good way to space out a class:

    PHP Code:
    // Correctly spacing a class with tabs to make it readable.
    class foo
    {
        public 
    $somthing;
        
        function 
    __construct()
        {
            
    // Constructor
        
    }
        
        public function 
    bar($bool)
        {
            if (
    $bool == true)
            {
                
    $this->something true;
            }
            
            return 
    $this->something;
        }

    Every time you open a new curly brace "{", add an extra tab, this will enable us to read code more easily and also you will know which brace is closing which blocks of code.

    Bye for now.

  2. #2
    PHP Witch laserlight's Avatar
    Join Date
    Apr 2003
    Location
    Singapore
    Posts
    13,915
    Unless there are objections or suggestions otherwise, I am making this a sticky.

    Note that style guidelines are always subjective. Feel free to use a different style, as long as you are consistent and keep to the spirit of what iceomnia suggested.
    Use Bazaar for your version control system
    Read the PHP Spellbook
    Learn How To Ask Questions The Smart Way

  3. #3
    Geek
    Join Date
    Jul 2007
    Posts
    780
    I'd like to note that, on my system at least, when I'm posting code manually here and hit Tab it skips on to the submit button, or the next field in the form, so if you're posting a sizable chunk of code manually, perhaps do it in Notepad or another simple text editor beforehand and then paste it in.

  4. #4
    Senior Member iceomnia's Avatar
    Join Date
    Oct 2007
    Posts
    181
    I should have mentioned that...

    As Horizon88 has quite accurately said, it is best to write your code in a text editor, I really like Dreamweaver as it colour codes the code for you.

    You can get a free trial at www.adobe.com

  5. #5
    PHP Witch laserlight's Avatar
    Join Date
    Apr 2003
    Location
    Singapore
    Posts
    13,915
    Many text editors and pretty much all IDEs have syntax highlighting, and many of them are available at zero price. Read Editor used for PHP for an existing list of editors used by PHPBuilder members.
    Use Bazaar for your version control system
    Read the PHP Spellbook
    Learn How To Ask Questions The Smart Way

  6. #6
    Not Yet Involved Shrike's Avatar
    Join Date
    Oct 2003
    Location
    The Eighth, Sursamen
    Posts
    2,278
    Just a quickie to illustrate what has become my coding style, somewhat similar to the PEAR coding standard.
    PHP Code:
    /**
     * $Id$ Subversion tag
     * @author Me
     * @package SomePackageName
    */
    class CamelCaseClassName
    {
      const 
    CONSTANTS_UPPER_CASE 1;

      public
       
    $vars_lowercase_and_underscore_separated;

      protected
       
    $access_modifiers,
       
    $grouped_together;
      
    /**
       * Javadoc style comments
       *
       * @param int $space_between_parens Just an example
       * @return void
       */
      
    public function functionsCamelCaseExceptFirstWord$space_between_parens )
      {
    // Curly braces on new lines

      
    }

    I use the Eclipse IDE which provides alot of useful features such as in-line Javadocs, code folding and so on. The above style fits in well with Eclipse's basic feature set.
    The Hundredth Idiot

  7. #7
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Contact Unit "Coping Mechanism"
    Posts
    22,534
    It should also be said that if you have having trouble with some code, you should cut and paste the code you're actually having trouble with, instead of trying to type it out again (and maybe making different mistakes).

    If you took laserlight's advice, you would already have made copies of the problem files, and then tried to remove as much as possible while still retaining the error.


    The implication is that you should be properly formatting your source code anyway. Remember that source code exists so that humans can read it, and while the computer doesn't care about how it's formatted the people who you want to help you probably do.
    Last edited by Weedpacket; 03-15-2008 at 01:33 AM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  8. #8
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    14,882
    Quote Originally Posted by Weedpacket
    ...
    The implication is that you should be properly formatting your source code anyway. Remember that source code exists so that humans can read it, and while the computer doesn't care about how it's formatted the people who you want to help you probably do.
    Not like the good(?) old days writing BASIC programs on my TRS80 with 4KB of RAM (yes, that is four (4) kilobytes), where every unnecessary space risked making my program too big. And as for comments...who had room for them!
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  9. #9
    Geek
    Join Date
    Jul 2007
    Posts
    780
    Quote Originally Posted by NogDog
    Not like the good(?) old days writing BASIC programs on my TRS80 with 4KB of RAM (yes, that is four (4) kilobytes), where every unnecessary space risked making my program too big. And as for comments...who had room for them!
    Please tell me you weren't the kid that strapped his calculator to his hip. :P

  10. #10
    High Energy Magic Dept. NogDog's Avatar
    Join Date
    Aug 2006
    Location
    Ankh-Morpork
    Posts
    14,882
    Nah, when I was a kid, there were no calculators, only slide rulers. I didn't actually use a portable, battery operated calculator until my freshman year of college (or maybe sophomore, I'm not sure). That was my roommate's Texas Instruments calculator which had come down in price to $100.00, and I don't think could do anything besides add, subtract, divide, and multiply and maybe had a square root function. (I was a music major, so it was just a cool toy to me.) Got my first personal computer (the Trash-80) several years later. It was so cool when I sold that to a sucker...I mean a friend and got my Atari 1200 with a whopping 64KB of RAM (and 32-color output to a TV for the monitor!). And a year later, I got a floppy disk drive for it and thought I'd died and gone to heaven (no more saving/loading programs to/from a cassette tape recorder).
    "Well done....Consciousness to sarcasm in five seconds!" ~ Terry Pratchett, Night Watch

    How to Ask Questions the Smart Way (not affiliated with this site, but well worth reading)

    My Blog
    cwrBlog: simple, no-database PHP blogging framework

  11. #11
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Contact Unit "Coping Mechanism"
    Posts
    22,534
    Hah, Sinclair were smart when they built my ZX81: each BASIC keyword was a single token and hence stored as a single character. Coding standards were enforced. You could fit quite a bit into 1kB that way.

    Meanwhile,
    "Why do half your punched cards contain only plain text?"
    "Comments"
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  12. #12
    Senior Member iceomnia's Avatar
    Join Date
    Oct 2007
    Posts
    181
    Just a quickie to illustrate what has become my coding style, somewhat similar to the PEAR coding standard.
    In adition to camelCase, you should always remember to use an upper case letter to define a "static" object, for example:

    PHP Code:
    class main
    {
        
    // declare a variable that can be called once the class
        // has been initialised.
        // Eg. $class->$publicVar;
        // ...and can be set from outside the class
        // EG. $class->$publicVar = $value;
        
    public $publicVar;
        
        
    // Declare a variable that can only be modified by a class method,
        // This var cannot be set externally, as like a sbove, but
        // can be called externally.
        // Eg. $class->$privateVar;
        
    private $pivateVar;
        
        
    // Declare a variable that can only be used within
        // the scope of the class and not called for from outside
        // This var cannot be set externally, or called externally.
        
    protected $protectedVar;
        
        
    // Declare a variable that can be called outside the class
        // without any initialisation of the class...
        // This var can be called or set externally, like so:
        // echo main::$StaticVar;
        // or
        // main::$StaticVar = $value;
        // However, cannot be called from inside the class with the $this keyword,
        // You must use self::$StaticVar;
        
    public static $StaticVar;
        
        
    // The constructor is always public, otherwise
        // you would not be able to initialise the class
        // Therefore, the "public" keyword is not required.
        
    function __construct() // No overload...
        
    {
            
    // Constructor
        
    }
        
        
    // Here's a way of both setting and retrieving the privateVar.
        
    public function setPrivateVar($str "")
        {
            if (
    $str != "")
            {
                
    $this->privateVar $str;
            }
            
            return 
    $this->privateVar;
        }
        
        
    // So therefore you can call this method (function), even if the
        // class is not initialised with $class = new main();
        // Like so: main::DoSomething();
        // Very useful, for when you may need to use this in another
        // class without haveing to initialise this class...
        // ALWAYS use an uppercase starting letter with static methods & variables.
        
    public static function DoSomething()
        {
            
    // Do Something...
        
    }
        
    // End main 
    Last edited by iceomnia; 03-15-2008 at 09:33 PM.

  13. #13
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Contact Unit "Coping Mechanism"
    Posts
    22,534
    Quote Originally Posted by iceomnia
    In adition to camelCase, you should always remember to use an upper case letter to define a "static" object, for example:
    Why? You can always tell a static property or method because they're always prefixed by a class identifier (a class name, or "self", or (from 5.3) "static".
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  14. #14
    Senior Member iceomnia's Avatar
    Join Date
    Oct 2007
    Posts
    181
    Well, it's personal preference really, just like camelCase is. But according to the people behind C++, general programing standards suggest that you should do so.

    ...and I know that C++ is not php, but since we have adopted camelCase, it seems logical to adopt this style for static methods (or functions) in php doesn't it?...

    ...Especially since, now we're using webservices in php, we should adopt the general programing standard for ease of compatibility etc, wouldn't you say?
    Last edited by iceomnia; 03-15-2008 at 09:30 PM.

  15. #15
    PHP Witch laserlight's Avatar
    Join Date
    Apr 2003
    Location
    Singapore
    Posts
    13,915
    Well, it's personal preference really, just like camelCase is.
    Indeed.

    But according to the people behind C++, general programing standards suggest that you should do so.
    Sorry, I am a C++ programmer but I have heard no such thing. The C++ Standard does not follow such a naming convention. Speaking of "general programming standards", Sutter and Alexandrescu's C++ Coding Standards recommend: "Don't overlegislate naming, but do use a consistent naming convention". They do suggest a simple naming convention to use if you cannot decide on your own naming convention.

    ...and I know that C++ is not php, but since we have adopted camelCase, it seems logical to adopt this style for static methods (or functions) in php doesn't it?...
    No. As Weedpacket pointed out, "they're always prefixed by a class identifier". Since the style makes no difference for readability, this could even be a case of overlegislating naming. If you do want to enforce something, enforce prefixing the class name, since PHP does allow static methods to be called using the syntax of non-static methods.

    ...Especially since, now we're using webservices in php, we should adopt the general programing standard for ease of compatibility etc, wouldn't you say?
    There is no such thing as "the general programming standard" where style is concerned. There are only style-related programming standards specific to an organisation, be it a team, a project, a company, or even a standards committee. Again, Sutter and Alexandrescu state: "Say only what needs saying: Don't enforce personal tastes or obsolete practices."

    Furthermore, they also advise:
    Do use consistent formatting within each source file or even each project, because it's jarring to jump around among several styles in the same piece of code. But don't try to enforce consistent formatting across multiple projects or across a company.
    In our context, this translates to: recommend that users be consistent with a reasonable formatting style when posting, but do not enforce a particular formatting style.
    Last edited by laserlight; 03-16-2008 at 03:27 AM.
    Use Bazaar for your version control system
    Read the PHP Spellbook
    Learn How To Ask Questions The Smart Way

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •