An alternative of Hungarian notation applied to PHP

For some cases, by example when you works on webservices or an ETL, you can be a little lost between all the variables you use, specifically arrays.
I developed a derivative of the Hungarian notation to prefix my variables and find myself there. This notation can be applied in php, but also to any other languages, especially non-typed.
There is the prefixing I use with PHP variables in that specific cases, depending on their type and design :

Scalar types prefix

  • $is, $b : boolean
  • $s : string
  • $i : int (unsigned)
  • $n : natural (signed int)
  • $f : float
  • $fd : float round to 1 decimals
  • $fc : float round to 2 decimals
  • $fm : float round to 3 decimals
  • $m : mixed.

Non-scalar prefix types

  • $o : object
  • $r : resource (PHP-specific)

Array, can be, by design, a collection of elements, or a single element. For me an “element” is an object-like data, stored as an associative array. While a collection if an array of elements.
So I can distinguish 3 different types for arrays :

  • $e : (array) Element (or Entry, or Entity) ; associative array containing data about an element.
  • $c : (array) Incremented Collection ; an array with auto-incremented keys containing elements. Means that the array keys don’t identify an element, event if the order to process it can be important.
  • $a : (array) Associative collection ; an array with associative & manually-assigned keys (like “hashes” in Perl ) containing elements.

For collections, I usually also put the variable in plural (or simply suffix with an s). I suggest to combine collection prefixes with the other prefix showing the values each entry contains :

  • $ca : incremented-collection of Associative collection
  • $cm : incremented-collection of mixed elements
  • $ae : associative-collection of array elements
  • $as : associative-collection of string elements
  • $am : associative-collection of mixed elements (each entry can contain different things)
  • $cbo : increment-collection of boolean OR objects. So we have to test if the entry is an object before processing it.

Semantic types :

  • $u : unsafe type or value, need to be checked or sanitized for security reason.
  • Can be combined : ie $us for unsafe string, with possible code injection.
  • $zo : string of encoded object
  • $zj : string of encoded json
  • $zh : string of encoded html entities, ie: ‘"’
  • $ts : timestamp (signed int)
  • $d : date, format ‘Y-m-d’ (string)
  • $dt : datetime, format ‘Y-m-d H:i:s’ (string)

I personnally try to avoid to prefix private members / functions with underscores.

Don't be selfish...Tweet about this on TwitterShare on LinkedInShare on FacebookShare on RedditEmail this to someone