Some PHP Tips for Beginners

Hey guys, here are a few tips that might help you, that in my opinion would be good to consider!

1. Use MySQLi functions instead of MySQL functions
You can use the functions procedurally or as an object, so the learning curve is very easy. A lot of the functions have very similar names. With MySQLi you can create prepared statements, you might not need them right now, but the option will be good later on. If you want to get a better head start than this, I would recommend learning PDO, but that has a hard learning curve.
http://php.net/manual/en/book.mysqli.php

2. Use descriptive camelCase $variables
A regular variable can be confusing if you read your own code later, $myvar or $item does not make much sense, unless you want to re-study your code a year later! So try to be descriptive and camelCase variables, it is a popular naming convention used in Java and Zend Framework. A variable would be something like this: $inputFileName
http://framework.zend.com/manual/en/coding-standard.naming-conventions.html

3. Master the Array’s and Multi-Dimensional Arrays
You will work with arrays a lot and they have a lot of power. When you understand how to re-arrange things and grab what you need you will see they are life-savers in many situations!

Tip: If you don’t assign a key, it will use a digit by default


// Enumerated arrays (Digits are used for the key)
$b = array ('dog', 'cat', 'fish', 10 => 255);
echo $b[0]; // Gives you dog
echo $b[255] // Gives you an error, because 255 is the value not they key!
$variable['key'] = 'value'

// Associative arrays (Words used for the key)
$c = array ('fish' => 'big', 'dog' => 'fat')
echo $c['fish'] // Gives you 'Big'
echo $c[0] // Gives you an error, the keys are associative not enumerated.

// Multi-Dimensional Array (An array that has more arrays in it)
$d = array('cat' => array(
     'brown', 
     'yellow', 
     'black'), 
    'dog' => 'none');

echo $d['cat'][0] // Grabs 'brown'
echo $d['cat']['yellow'] // Error, yellow is the value! 
echo $d['dog'] // Gives you 'none'

Some great array functions to start with:
array_pop
array_shift
array_slice
implode
explode

  • and some of the sorting ones

http://php.net/manual/en/ref.array.php

4. Comment your code
You don’t have to get obsessive over it, but it might save you a lot of sweat from your forehead someday trying to figure out what you were doing. An example of a comment is with phpDoc and it looks like this:


/**
* @desc  This function does nothing 
*/
function Nothing()
{
    return 0;
}

Alternatively you can also name all your arguments like this:


/**
* @desc  This function does nothing 
* @var <str> $strInput An input string that does nothing right now...
*/
function Nothing($strInput)
{
    return 0;
}

This way you can write your projects documents while you program it. It takes a little effort and habit to get into, but it is going to help you someday.

5. When you are bored, practice OOP
Objects will change your programming life and make you capable of many more things. It is tricky to learn at first, and tricky to see the value at first. But after a few months of doing OOP you will be one of the happiest people alive.

Even if you don’t totally understand what you are doing, doing a little bit each day will stick in your mind and you’ll be able to recall things you’ve read about and the understanding comes together like building blocks.

http://www.php.net/manual/en/language.oop5.basic.php

6. Ask stupid questions if Google wont help you
Its easiest to ask a question where your problem rests, rather than sending a huge 300 line copy paste :slight_smile: I noticed when you ask short and simple questions people are on it like a dog on a raw bone, they want to be the first to answer. But people tend to avoid the lengthy long questions where they must dig through a ton of code. So try to find where your error lies, and keep it simple.

Nice tips JREAM, arrays and multi-dimensional arrays is a winner to know as from experience its one of the most helpful codes PHP has to store heaps of info :stuck_out_tongue:

Maybe download te documentation from http://www.php.net/docs.php

start of every project:



   set error_level(E_ALL); 
   ini_set('display_errors','On');


I find that trying to get rid of the warnings is the best way to learn the language.

Great advice, that’s exactly what I do :cool:


<?php
error_reporting(-1);
ini_set('display_errors', true);

Ah wow, thanks, I didn’t know about that. :slight_smile:

Whoops, it has been a long day sweating over the keyboard :slight_smile:

PHP accepts the ‘On’ parameter in ini_set(‘display_errors’, ‘On’), why use true and why do you set the parameter to -1 instead of E_ALL? Am I missing something?

Pretty sure E_ALL doesn’t include strict, the docs state -1 reports ALL errors, so that’ll do for me. :slight_smile:

Why true? The setting is blatantly a boolean, so I use true. Just personal semantics I guess.

Huh, that’s weird.


ini_set('display_errors', $var);

If you set $var to true it will display the errors, if you set it to false it won’t.
If you set it to ‘On’ it will display the errors, which is to be expected since (bool)‘On’ is true. However, if you set to ‘Off’ (which is also logically true) it doesn’t display the errors.

It seems the code is something like this:


function ini_set($key, $value)
{
   if ($value==='Off') $value=false;
   // set internal value here
}

As for the error_reporting -1, AFAIK that does indeed mean ALL possible errors. Now, and in the future. That is, if there are ever levels added above E_STRICT these will be thrown as well.

It looks like this is the logic used…

static PHP_INI_DISP(display_errors_mode)’, lines 303 -> 347.

Lines 262 -> 289 looks pretty interesting too, they detail how PHP re-reads the user supplied setting.

I run WAMP and call http://localhost in my browser.

Another useful setting is to define a LOCALHOST variable.

LOCALHOST is used throughout my scripts to cater for different configurations when the scripts are uploaded to the server.


  
  if(! defined('LOCALHOST')) // prevent error if already defined
  {
     define('LOCALHOST', 'localhost' === $_SERVER['SERVER_NAME']);
  }

  // PHP errors and warnings are logged but not visible to punters.
  error_reporting(-1); // catch all including E_STRICT

  // The ini_set(...) when used online prevents any errors 
  // and especially paths from showing 
  // on the off-chance an error is encountered.
  ini_set('display_errors',LOCALHOST);



  // mysql online defaults settings
  $dbhost = 'my_host';
  $dbase  = 'online_database_name';
  $dbuser = 'online_user_name';
  $dbpass = 'online_password';
  if(LOCALHOST)
  {
    $dbhost = 'my_localhost';
    $dbase  = 'localhost_database_name';
    $dbuser = 'localhost_user_name';
    $dbpass = 'localhost_password';
  }
  
   $dbh=mysql_connect
   (
      $dbhost = 'my_localhost';
      $dbuser = 'localhost_user_name';
      $dbpass = 'localhost_password';
   )
   or die('Cannot connect to the database because: ' . mysql_error());
   mysql_select_db($dbase);


The above code eliminates the need to have two configuration files
and especially uploading the wrong file and over-writing the online configuration file.

Have you thought about just having one, central, point for this change in behaviour?

<?php
error_reporting(-1);
ini_set('display_errors', true);

define(
  'IS_PRODUCTION',
  true
);

$config = ConfigurationFactory::Build(
  IS_PRODUCTION ? 'production.ini' : 'development.ini'
);

?>

No. Use PDO. There’s a movement in the dev group to remove all of the older db access libraries out of PHP Core and into PECL starting with PHP 5.4, which means they will not always be available because they won’t be compiled into all distributions, probably starting around PHP 6.1

2. Use descriptive camelCase $variables

More importantly, follow conventions. $i is a generic incrementing index of a loop, if loops are nested then $j, then $k is used. Variable names that have to be typed a LOT need to be shorter. Abstract functions can and should have abstract variable names.

Constants are ALL_CAPS. Class names should be capitalized, functions are never capitalized. Older PHP code (4 or earlier) starts method and member names with an _ to mark that they are private or protected - don’t do this, actually make them private or protected.

Camel case isn’t the only way - underscores_are_just_as_valid.

Like E_DEPRECATED, E_USER_DEPRECATED (As of PHP 5.3)

My advice is to read this and try not to accidentally do anything it mentions by mistake: http://freeworld.thc.org/root/phun/unmaintain.html

Instead of defining it in every project separately I have it defined in the PHP auto_prepend_file on my development PC.


define('IS_DEV_SERVER', true);

and then in the project bootstrap I have


defined('IS_DEV_SERVER') or define('IS_DEV_SERVER', false);

And then just check in the code for defined(‘IS_DEV_SERVER’) && IS_DEV_SERVER for things that should only be ran on development servers (extended logging, different configurations, etc)

The advantage of this is that if you ever decide to add more development servers you can just copy the auto_prepend_file to the new server and all websites running there switch to development mode instantly.

Of course on a live server IS_DEVELOPMENT_SERVER isn’t defined , so projects running there will never be in development mode, unless I define IS_DEV_SERVER to be true for a particular project.

I guess you could say this is a generalization of the solution John_Betong uses :slight_smile:

7 Don’t let the cat in the room with you

It will only start accidentally typing with its foot/tail, and you should be aware of the risk that it might write better code than you, deflating your ego. Also, they molt hairs everywhere which can get between the keyboard keys or make you sneeze.

The link is absolutely hilarious and raised frequent belly laughs nearly bringing tears to my eyes.

This is my favourite:

Reverse the Usual True False Convention

Reverse the usual definitions of true and false. Sounds very obvious but it works great. You can hide:
#define TRUE 0
#define FALSE 1
somewhere deep in the code so that it is dredged up from the bowels of the program from some file that noone ever looks at anymore. Then force the program to do comparisons like:
if ( var == TRUE )
if ( var != FALSE )


Originally Posted by AnthonySterling
Have you thought about just having one, central, point for this change in behaviour?
Instead of defining it in every project separately I have it defined in the PHP auto_prepend_file on my development PC.



and

Originally Posted by ScallioXTX


I guess you could say this is a generalization of the solution John_Betong uses

As mentioned by Cups there are many ways to skin a cat :slight_smile:

The original post was “Some PHP Tips for Beginners” but now it is getting a bit too hairy for beginners.

Wow that’d be cool. I suggest mysqli because PDO is a more difficult learning curve, but it’s worth it to go the distance :slight_smile:

Ooh, that’s a very clever solution to the ‘to debug or not to debug’ question.
I think I’ll copy that!

This is such a useful thing to know. I’ve bumped into this problem several times, never thought about it really but this would prove very useful. I’ll have a play with it later. Cheers for the tip.

I noticed an error with the script, try this instead:



 // mysql online defaults settings 
  $dbhost = 'my_host'; 
  $dbase  = 'online_database_name'; 
  $dbuser = 'online_user_name'; 
  $dbpass = 'online_password'; 
  if(LOCALHOST) 
  { 
    $dbhost = 'my_localhost'; 
    $dbase  = 'localhost_database_name'; 
    $dbuser = 'localhost_user_name'; 
    $dbpass = 'localhost_password'; 
  } 
   
   $dbh=mysql_connect ($dbhost, $dbuser, $dbpass) 
   or 
   die('Cannot connect to the database because: ' . mysql_error()); 

   mysql_select_db($dbase);