Thoughts, rants and commentary of a simple man

PHP operators: double and single arrow

Posted on March 4th, 2009 in Geek Stuff,PHP,Programming,Web Development | 33 Comments »

Someone recently asked a question on the Professional PHP Programmers Google Group that I thought was interesting. This question interested me for a few reasons:

  1. The PHP manual is a very good manual and usually covers things like this; and,
  2. I remember asking this very question when I first started developing.

Hi all, I’m new to the mailing list, and new to php, and new on programming.

Here I go:

I have a question but I was unable to find an answer for this on the web. Because I have no Idea how to ask this on a search engine.

What’s the meaning of -> and => on php?

As good as the PHP manual is, and as well documented as the operators in PHP are, the documentation on these two operators is lacking severely. Even naming is horribly lacking for these two operators, as a recent Twitter chat shows:

More on the operators used in PHP can be found at http://us3.php.net/manual/en/language.operators.php. Unfortunately, these operators will not be found there. So to assist in explaining what these operators are and what they do, lets dig a little deeper in the world of cryptic symbols that remain unnamed in PHP. Shall we?

The double arrow operator, “=>”, is used as an access mechanism for arrays. This means that what is on the left side of it will have a corresponding value of what is on the right side of it in array context. This can be used to set values of any acceptable type into a corresponding index of an array. The index can be associative (string based) or numeric. So if I have an array like:

<?php
$myArray = array('Big', 'Small', 'Up', 'Down');
?>

Then in effect the code is saying:

<?php
$myArray = array(
  0 => 'Big',
  1 => 'Small',
  2 => 'Up',
  3 => 'Down'
);
?>

This is not a real surprise seeing as arrays in PHP are numerically indexed, zero-based arrays by default. But what if you wanted a hash of keys and values? Like when passing something as a form or in a querystring or reading results from a database? Well then, you would want to associate a key to a value in the array, or something like:

<?php
$myArray = array(
  'Robert' => 'Big',
  'Bobby' => 'Smart',
  'PHP' => 'Rocks'
);
?>

Now you have a hash of values assigned to indeces using the double arrow, or array value assignment, operator (“=>”).

The object operator, “->”, is used in object scope to access methods and properties of an object. It’s meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here. We’ll talk about that a little more in just a bit.

If you come from a background in object oriented programming then you know that every object has a way to access the methods and properties of the instantiated object. In most languages that is the dot operator (“.”). In PHP the dot operator has completely different meaning (it is used to concatenate strings) so don’t use that for object scope resolution. Instead, after instantiating an object, access its methods and properties using the object operator, like this:

<?php
$obj = new MyObject(); // Create a new instance of MyObject into $obj
$obj->thisProperty = 'Fred'; // Set a property in the $obj object called thisProperty
$obj->getProperty(); // Call a method of the $obj object named getProperty
?>

Now, getting back to object basics, remember I said that instantiated was a key term? The reason for that term is because there is another operator related to scope resolution than can be used but it is neither an arrow nor can it be used on objects. It can only be used on classes (this is as of PHP 5 – since PHP4 has already been fed to the dogs we are only going to talk about PHP 5). Class scope resolution is identified by the Paamayim Nekudotayim, or double colon, operator (“::”).

If you use a static class or static methods or properties within a class, you would not use the object operator (“->”) but would instead use the scope resolution, or double colon, operator, like so:

<?php
MyClass::$staticProperty = 'Fred'; // Sets a values into the static class
MyClass::getStaticProperty(); // Gets a value from a static method
?>

Now that you have the power of operators at your fingertips, even if in a very basic sense, you can get busy with assigning and accessing goodies in arrays, objects and classes. And remember as you use these that nothing at all can replace the learning you would get from trying them out, especially when you try to use them the wrong way (error messages can be quite educational).

If I could leave you with one bit of advice it would be to get your hands dirty on some of them and see what the parser tells you when it chokes on one (or more) of them.

And have fun. Stepping in to object oriented programming can be a frustrating, painful experience for some. But it is definitely a rewarding one.

Back to top

Handling multiple Sybase result sets in PHP on Ubuntu 8.10

Posted on February 17th, 2009 in Geek Stuff,LAMP,Open Source,PHP,Web Development | 2 Comments »

A long time ago I was tasked with creating a PHP application that would talk to our Sybase database that drives our entire enterprise at work. This is not normally a big thing to do as one can simply enable the Sybase extension for PHP and have a database connection generally within minutes. However there was one thing that was an absolute necessity in this application that made it significantly more difficult to get it working: some parts of the application would be reliant upon stored procedures that returned multiple result sets.

First off let me say that any time you have the option to build stored procedures for your database quieries, do it. They are faster, safer, compiled and centralized and they keep your code from being littered with query builders all over the place. That said, this is neither the time nor the place to talk about the merits of stored procedures in application development. Just know that where I work there are no direct queries ever allowed to touch our database servers.

Knowing that I had to work under the requirement of handling multiple Sybase result sets I set out to find out how to do it and what I found was alarming. Few database extensions in PHP handle multiple result sets. In fact, as I was looking around it seemed that only the MySQLi extension and the SQL Server extension handled multiple result sets. But after a little searching around I found something called the “PHP Sybase CT driver enhancements” project on Sourceforge that essentially provided prepared statement handling and multiple result set handling for the PHP Sybase Extension. However, after trying to install it it became evident that the extension, as it was written, was still not usable in the state it was offered up for download in.

Not to worry, I have modified the package for compiling within a PHP 5 environment and have made a few changes to it that should allow it to be used as is. The source code archive file can be downloaded (in tar.gz format) by clicking here.

Please read the notes on this source code before installing it!

Before installation

Before we get started we need to cover a few assumptions:

  • You have a licensed copy of Sybase Adaptive Server
    I have not tried this against any Sybase database server other than Adaptive server.
  • You have the Sybase client installed or at the very least have the installer available
    For this exercise we are using a Red Hat RPM of the Sybase 12.5 client. Yes, we are installing on Ubuntu, which is essentially Debian and therefore does not use RPM files, but we will burn that bridge when we come to it.
  • You are comfortable building PHP extensions from source
    There is no way around this. In order to get this to work you will need to be able to build from source.
  • You have the php-devel package installed on the machine you building this extension for
    If you don’t have it, a quick sudo apt-get install php5-dev should do the trick. This will be necessary to build the Sybase extension from source.

Installation instructions

Ok, these are the steps I took in order to build the enhanced Sybase extension for PHP on my Ubuntu 8.10 desktop machine starting with Sybase ASE client and common packages in Red Hat RPM format.

  • Convert the Sybase 12.5 OpenClient and Sybase 12.5 Common RPM archives to DEB packages and install them
    To do this I used the alien package converter tool and, while inside the directory where the RPMs were living, issued the following command:
    $ alien -k sybase-common-12.5.0.1de-1.i386.rpm
    $ alien -k sybase-openclient-12.5.0.1esd-1.i386.rpm

    This created two new archives, in the directory I was in, in debian format named

    1. sybase-common-12.5.0.1DE-1_i386.deb
    2. sybase-openclient-12.5.0.1ESD-1_i386.deb

    I then issued the following commands to install them:
    $ sudo dpkg --install sybase-common-12.5.0.1DE-1_i386.deb
    $ sudo dpkg --install sybase-openclient-12.5.0.1ESD-1_i386.deb

    This made a directory named sybase-12.5 in the /opt directory.

  • Prepare your environment to build the extension
    To make things easier (and a little more compatible with the Red Hat way of doing things) I created a link inside of /top called sybase and pointed it to the sybase-12.5 directory.
    $ cd /opt
    $ ln -s -T /opt/sybase-12.5 sybase

    I then had to export some environment vars that are needed by the extension and the web server in order to handle communication with the Sybase server:
    $ export SYBASE=/opt/sybase
    $ export SYBASE_OCS=OCS-12_5
    $ export PATH=/opt/sybase/OCS-12_5/bin:$PATH
    $ export LD_LIBRARY_PATH=/opt/sybase/OCS-12_5/lib:/opt/sybase/OCS-12_5/lib3p:$LD_LIBRARY_PATH
    $ export INCLUDE=/opt/sybase/OCS-12_5/include:$INCLUDE
    $ export LIB=/opt/sybase/OCS-12_5/lib:$LIB

    Yes, I know that each one of these commands could have been placed in a file and sourced, but for some reason source is not available to my installation of Ubuntu so it was in fact easier and faster for me to do it this way. Do this how you will, but remember the values because you will need these later.

  • Build and install the php-sybase-ct extension from source against the Sybase client you just installed
    Remember that package I told you about earlier? The one that I said you could download? If not, get it now and unpack it to a directory somewhere where you have permission to unpack stuff on your system. For me, it was ~/Temp.

    Change to the directory you unpacked the source code to and configure it for make and installation using the php-devel package:
    $ cd ~/Temp
    $ phpize
    $ ./configure --with-sybase-ct=$SYBASE/$SYBASE_OCS
    $ make
    $ sudo make install

    Find out where your extensions directory is on your machine and quickly check it to make sure there is a php_sybase_ct.so file living in it. On my machine the extension directory is /usr/lib/php5/20060613+lfs/. Yours may be different.

    At this point you can safely do a sudo make clean but you might want to hold off on that until it is all working in case you need to rebuild at all. It does happen from time to time. Just sayin’.

  • Configure PHP to use the new extension
    Now we need to tell PHP to use the new extension we just built. To do that we need to create an ini file for the extension and put it inside of the extensions directory where PHP can find it. On my machine PHP looks for ini files to parse in /etc/php5/conf.d/ so naturally that is where I am going to go to to tell PHP to use this extension.

    $ cd /etc/php5/conf.d/

    Now we need to create an ini file and put into a directive to load the extension. You can use whatever editor you like. I prefer to use vim:
    $ sudo vim sybase_ct.ini

    Inside this file place the following two lines:
    ; Enable the sybase extension
    extension=sybase_ct.so

  • Configure your environment to load the correct environment variables whenever the machine starts
    This one caused me fits for a long time in Ubuntu. In order to ensure that you can use the Sybase extension from both the CLI and the web server you will need to take all of the environment variables that exported prior to building the extension and place them in both the /etc/profile startup script AND the web servers environment variable setting script. This caused countless hours of frustration and anger for me and I hope I can save you some angst with this little snippet.

    Add the environment vars to /etc/profile. You can use any editor you like. I like vim:
    $ sudo vim /etc/profile

    At the end of the file add the environment vars:
    export SYBASE=/opt/sybase
    export SYBASE_OCS=OCS-12_5
    export PATH=/opt/sybase/OCS-12_5/bin:$PATH
    export LD_LIBRARY_PATH=/opt/sybase/OCS-12_5/lib:/opt/sybase/OCS-12_5/lib3p:$LD_LIBRARY_PATH
    export INCLUDE=/opt/sybase/OCS-12_5/include:$INCLUDE
    export LIB=/opt/sybase/OCS-12_5/lib:$LIB

    Now add these same entries into your web server’s environment variables. I am using apache and assuming you are to. If not, consult your web server’s documentation for how to do this:
    $ sudo vim /etc/apache2/envvars

    Now add these entries to the end of the file:
    export SYBASE=/opt/sybase
    export SYBASE_OCS=OCS-12_5
    export PATH=/opt/sybase/OCS-12_5/bin:$PATH
    export LD_LIBRARY_PATH=/opt/sybase/OCS-12_5/lib:/opt/sybase/OCS-12_5/lib3p:$LD_LIBRARY_PATH
    export INCLUDE=/opt/sybase/OCS-12_5/include:$INCLUDE
    export LIB=/opt/sybase/OCS-12_5/lib:$LIB

  • Restart your web server
    Like everything that involves a change to the PHP environment or configuration on your machine, restart the web server. I am assuming this is being built upon an apache server. If not, you will need to know how to stop and start your web server or, at the very least, know how to reboot your machine:
    $ sudo apache2ctl stop
    $ sudo apache2ctl start

    Run a PHP info page or CLI call to see if it is loaded:
    $ php -m

    You should see sybase_ct. If not, something went wrong. If so, you are now golden.

At this point you should be able to run queries against your Sybase server AND handle multiple result sets using the sybase_next_result() function. There is no documentation for this function, but a quick read through of the mssql_next_result() function will tell pretty well how to use it.

Enjoy! And if this was at all helpful please leave a comment to let me know.

Notes on the PHP Sybase CT Enhanced extension

Some things to keep in mind when using this extension:

  • This extension is coded in PHP 4 source.
  • When I got my hands on it the code was still much in development phase. Not much has changed about that other than I removed debug output from it.
  • It does not handle connection failure well when the server does not respond. So unwell in fact that internally it causes segmentation faults and results in blank web pages upon failure. I do not know how to fix that.
  • If you know how to program in c or want to make it better, please feel free to do so. I have contacted the original authors of this extension and of the three only one has done any real work on it and none have worked on it in the last five years and really do not intend to. I was given permission to distribute it and modify it. But I really do not know what I am doing in c. Yet. 😉
Back to top

Coffee, WiFi and coding

Posted on January 31st, 2009 in Geek Stuff,Web Development | No Comments »

Today I had the pleasure of working. I know, that sounds really weird, but it is true. It was a pleasure. The reason it was pleasurable is because I was able to work outside of the home in a fairly quiet place that served all the coffee I could drink for $1.50.

Thanks to Mission Coffee and their free WiFi internet connection I was able to spend about three and half hours working on a project that I have spent entirely too much time on already but seriously needs to get done. It was clean, quiet, conducive to programming work and, well, it had coffee. Lots of it. And it was only $1.50 for never ending cup.

It was a nice feeling to get out of the house today. Usually as I am at home working I get derailed by the screams of children fighting or someone needing something. Being out meant that the distractions that I am faced with at home were virtually non-existent (save for guy that sat behind me and talked to himself in a quasi-farci-spanish mix). I had an entire table to myself, off in a little corner, where I wasn’t messed with by anyone. Mostly.

After about three and half hours I was asked to move because the wall I was sitting next to was getting artwork hung on it. As soon as I stood up I realized that it was time to get home. It just seemed right to be done at the time. And I have no regrets. The day was productive, the environment was nice and the coffee was great.

So if you are ever in Fremont and need a coffee joint to sit at and spend some time on the Internet, hit up Mission Coffee. You’ll be glad you did.

Back to top

Fun with PHP

Posted on July 24th, 2008 in PHP,Web Development | 4 Comments »

Every now and again someone writes a line or two of code that really makes me smile. Such is the case with this outcome determinating and decision making class below. This code is being reproduced, with or without consent, from the PHP Developers Network‘s own scottayy.

<?php
/**
 * Coin flipper class helps determine outcome of situations in which an outcome
 * cannot be decided by sheer manpower alone.
 * 
 * @author Scott Martin <scottayy@devnetwork.net>
 * @license None, don't even try to use this or your hair will turn yellow
 */
class coin {
	/**
	 * The outcome determinators
	 * 
	 * Each invocation of this object will require a determinator upon which the
	 * object relies to build a determined outcome. These are those determinators.
	 * 
	 * @access private
	 * @var array
	 */
	private static $_sides = array('heads', 'tails');
 
	/**
	 * The determinating method
	 * 
	 * This method, when called, invokes a determination sequence and returns a
	 * determined value for use in decision making.
	 * 
	 * @access public
	 * @return string Randomly selected determinator
	 */
	public static function flip() {
		// Quick, randomize me some determinators
		shuffle(self::$_sides);
 
		// Quick, offer it back before it gets angry
		return self::$_sides[mt_rand(0, 1)];
	}
}
 
/**
 * We should always test our determinating decision establisher
 *
 * 2,4,6,8 You know you want to determinate
 */
echo coin::flip();
?>

For those that just have to have an object to instantiate (and you know who you are), there is this lightly modified version for your obsessive/compulsive selves:

<?php
/**
 * Coin flipper class helps determine outcome of situations in which an outcome
 * cannot be decided by shear manpower alone.
 * 
 * @author Scott Martin <scottayy@devnetwork.net>
 * @license None, don't even try to use this or your hair will turn yellow
 */
class coin {
	/**
	 * The outcome determinators
	 * 
	 * Each invocation of this object will require a determinator upon which the
	 * object relies to build a determined outcome. These are those determinators.
	 * 
	 * @access private
	 * @var array
	 */
	private $_sides = array('heads', 'tails');
 
	/**
	 * The determinating method
	 * 
	 * This method, when called, invokes a determination sequence and returns a
	 * determined value for use in decision making.
	 * 
	 * @access public
	 * @return string Randomly selected determinator
	 */
	public function flip() {
		// Quick, randomize me some determinators
		shuffle($this->_sides);
 
		// Quick, offer it back before it gets angry
		return $this->_sides[mt_rand(0, 1)];
	}
}
 
/**
 * We should always test our determinating decision establisher
 */
$coin = new coin;
 
/**
 * 2,4,6,8 You know you want to determinate
 */
echo $coin->flip();
?>

See, just looking at that code makes you want to smile doesn’t it? Geeks are great.

Back to top

Making navigation menus using CSS

Posted on June 25th, 2008 in CSS,Geek Stuff,Mark Up,Web Development | No Comments »

A recent Sitepoint article by Rachel Andrews, Director of edgeofmyseat.com, outlined some pretty Nifty Navigation Tricks Using CSS. Anyone that wants to learn to make some pretty cool tabbed, button or vertical bar navigation lists should give this article a read through. It is a pretty well written article and has a great deal of code that can be easily copied and pasted for your development pleasure.

For four pages it reads very fast. It is easy to follow and the examples are practical. I wish there were some working samples of the code, but still, it is a good teaching tool for those that have yet to dive into CSS based navigation lists (and you should get into it, as CSS is designed for such things).

For those that want a huge assortment of samples, code and really cool lessons, check out Stu Nicholls’ CSS Play. This site is an amazing reference for learning the art of cross-browser compatible CSS. There are menus, layouts and much more available to learn from and even use, in many cases without even a link back to him, though it is always a good idea to give credit where credit is due.

So if you are in need of a little CSS learning fix, hit these references up. You will enjoy them and, in the case of Stu Nicholls, may even make them part of your normal daily web development toolset.

Back to top

Fun with PHP and Simple XML – Amber Alerts

Posted on June 17th, 2008 in American Idol,Geek Stuff,On Marriage,PHP,Web Development | No Comments »

A few weeks ago I was toying with XML. I had a few minutes to spend teaching myself so I decided that I would use that to work on something that I desperately need to work on. XML.

And what better way to learn a little XML stuff that on the Amber Alert system? So I began my journey.
Continue reading »

Back to top

New blog theme – Dark Sky

Posted on June 16th, 2008 in Geek Stuff,This Blog,Web Development | No Comments »

As much as I loved my Chocolate Ocean theme that I developed a few months ago…

Chocolate Ocean theme by Robert Gonzalez

… I thought it was time for a change. So I changed.

My theme that is.
Continue reading »

Back to top

Code monkey like design patterns lots

Posted on May 29th, 2008 in Geek Stuff,PHP Design Patterns | No Comments »

I was thinking today that though I carry the title of Web Developer around with me wherever I go I have not been developing for the web much the last few months. Come to think of it, I cannot say that I have developed anything for the web in about five months or so.

Don’t get me wrong. I have been coding PHP like a mad penguin with 20 hands and an incredible itch at the tip of his fingers. Its just that the code I have been writing has been either framework code that drives web apps or CLI code that will be used for integration projects from the command line or cron.

And I absolutely love what I am doing. I have been employing design patters almost as though they came straight from a book. Without even knowing I was doing that.

And it made perfect sense to do it. Little modular classes that are built of maybe two methods and a property each that totally allow for expansion later just by adding the controller and the model. You just gotta love it.

And because I have had the opportunity to do so, I have been using vi(m) quite a bit more than I have in the past. In fact, today I used nothing else. And I was totally thrilled to use it.

I felt faster and way more in control without having to touch my mouse. And I was able to code, shell out, process SVN commits, file searches, CLI stuff… everything I needed to do without ever leaving my editor and without ever touching my mouse. How awesome is that?

I think my zeal for the type of coding is that I felt like a programmer today. Not a script kiddie, not a PHP n00b, but a programmer. A guy who writes code then implements it and instantiates it at the CLI to watch (you ready for this?) absolutely nothing come to the screen – because that is how we want it to work.

Yeah, I love being a geek. And it doesn’t take much to make me happy as a geek. A sweet little editor, a freaking rad OS and a great programming language like PHP. Oh yes, color me happy. And color me geek.

Back to top