In your work with classes, one of the most important things to understand is the difference between static and non-static methods and properties. The key distinction is that static properties exist in the context of the class, and non-static properties exist only in the context of an object.
Accessing static methods and properties from your scripts is easy. If they’re public, just use the name of the class, followed by a double colon, followed by the static property or method you’re accessing. For properties, you need to include the dollar-sign. Without the dollar-sign, PHP looks for a class constant with that name. Here’s a class called StaticExamples:
{show example}
It defines a static property called ‘$helloWorld’. Over here in my test script:
{show test script}
, you can see I just write StaticExamples::$helloWorld to access it. Here’s the output:
{show output}
Static methods cannot access non-static properties and methods, because no object context exists for them. For a static method, the variable $this has no meaning, and because it has no meaning, there is no point of reference by which a non-static method or property can be called. At least, not directly. I’ll explain this more at the end.
On the other hand, non-static methods have no problem accessing static properties and methods. With static properties, if it gets changed at one part of the script, that change is reflected anywhere else that property is checked. I realize with a name like static, you’d think it couldn’t change at all, but static properties act just like regular variables. And actually, they’re often a good replacement for global variables.
So, consider this class:
{show example}
It defines a static property called $_changeme, a non-static property called _changeMeNS (the NS stands for non-static), and two non-static methods called setProps and getProps.
Those two non-static methods have to be invoked on instances of the StaticExamples class. Notice that once you call setProps with 2 arguments, it sets the static property $_changeMe to the first argument, and the non-static property _changeMeNS to the second argument.
Here’s a test script I wrote to go along with this lesson.
{show example}
The first thing it does is create three objects of the StaticExamples class. Then it calls the setProps method on each. Once it’s done that it calls the getProps method on each and displays their outputs. Let’s look at that now.
{switch to output}
Notice that the property labelled ‘static’ is a 3 on all of them, but they each have a different ‘non-static’ property. The reason for this is that only one StaticExamples::$_changeMe exists. And every call to setProps was also setting the $_changeMe variable. And now that I’m checking that variable, only the last value of $_changeMe exists.
As for the ‘non-static’ properties, they persist with the objects where they were set. So $SE1’s non-static property is still a 1, and $SE2’s non-static property is still a 2. Each object contains its own copies of its non-static properties, but they all accessed the exact same static property.
Now, looking back at the code, I want to point out the keyword ‘self’. It’s sort of like a static equivalent to ‘$this’. Each time I used ‘self’ I could have used the full class name ‘StaticExamples’ instead. I used ‘self’ because it’s a convenient shorthand for accessing static methods and properties from within the context of the class.
Now, a static method cannot access a non-static method or property directly, as I explained before. See my static method ‘doSomething’?
{show example}
It’s going to trigger a fatal error as soon as I try to use it. Watch:
{type StaticMethods::doSomething(); into test script}
{show output containing fatal error}
However, if you really wanted to, you could create a static property which is itself an object of your class, and then you could use that static property, within your static methods, to run non-static methods and access non-static properties.
Notice I’ve written 2 more methods in my StaticExamples class, called setPropsStatic, and getPropsStatic. They’re similar to setProps and getProps, but can be called from a static context.
{show example code}
The way they work, is they first check whether the variable $_instance, a private, static property, is null or not. If it is, they set it to a new object of StaticExamples. And that property will still be set the next time one of these methods looks for it. Next they run whatever code they need to. Notice in ‘setPropsStatic’ it’s using self::$_instance to access a private, non-static property. When a static method creates an instance of its own class, it can use that instance object as a handle for accessing private and protected methods or properties on it. We’re going to use that fact later when I show you how the Singleton pattern works.
Now, going back to my test script, I’ll put StaticExamples::setPropsStatic(0,0); in front of my call to $SE1->setProps, and I’ll stick StaticExamples::getPropsStatic(); right before $SE1->getProps. Now let’s look at how the output has changed.
{show output}
Notice, the static property on getPropsStatic is a 3, same as all the others. But it’s non-static property is a 0, just like when it was set. That’s because in the context of StaticExamples::$_instance, the property _changeMeNS has only been set one time.
The developers of PHP were actually taken a bit by surprise when object-oriented programming caught on the way it did within the PHP community. Objects were added as an afterthought to PHP 3, and were little more than syntactic sugar for associative arrays. PHP 4 brought some advancements in object support, but with PHP 5, the language has finally graduated into a completely respectable object-oriented language.
Among the features that you expect to find in object-oriented languages is the ability to limit access to your objects’ methods and properties. The goal here is to avoid letting your scripts get into trouble by messing with things they don’t need access to.
As a for instance, suppose you have an object that’s responsible for handling your database transactions. And on this object there exists a property called ‘dbConnect’ whose purpose is to contain the resource that will let PHP run queries on a database. And you’ve done a great job putting together a class that will execute SQL queries, handle transactions, do updates, and really is just an all around beautiful piece of code. And you’d like to ensure that this dbConnect property, one that your class sets up in the constructor and then makes use of in a few key functions, only ever has the value you expect it to.
But in PHP 4, you would just have to write strongly-worded comments and hope that none of the people on your project would be foolish enough to try and get the dbConnect property directly, thereby completely by-passing your class’s way of doing things securely and efficiently. Or worse yet, have a script go in and directly modify the value of dbConnect. After all, you don’t want dbConnect to change unless the database name, host, user, or password were changed too. If an outside script modifies it directly, your object may not actually be running commands on the database it thinks its running commands on, and that might lead to a whole cascade of errors.
So to deal with this type of situation, PHP 5 says you can now specify that a class has certain methods or properties that can only be accessed by the class itself. All you have to do is put the keyword ‘private’ in front of the declaration.
As a convention, I recommend you put an underscore in front of your private or protected properties and methods. It’s a nice way to know, at a glance, whether you’re dealing with something that’s public or not. It’s a pretty common convention. I don’t know where it started, but it’s one I’m quick to endorse. {show example class definition}
Now, the obvious question you’re probably asking, is what’s the difference between private and protected? Well, neither one can be invoked by an outside script, but while private methods and properties can only be invoked by the classes that declared them, protected properties and methods can also be invoked by the children of the classes that declared them.
So, if _protectedMethod is a protected method on the class ParentClass, and ParentClass is extended by a class called ‘ChildClass’, then an object of type ‘ChildClass’ would be allowed to invoke $this->_protectedSpecial(). {show example}
On the other hand, ParentClass also defines ‘_privateMethod’ as a private method. If a ChildClass object tries to invoke $this->_privateMethod() it will trigger a fatal error. {uncomment call to _privateMethod and then show example triggering error}
However, while this is probably the most common way of accessing a protected property or method from a child class, it doesn’t have to be in the context of “$this” in order to work. Consider this next example: {show example method}
$parent = new ParentClass();
$parent->_protectedMethod();
Then in the context of being on ChildClass somewhere, this code will execute without an error. {show output from method accessing protected property and method this way}
{while explaining next P, show method declaration with no scope keyword, access it in public context, then go back and put keyword ‘public’ in front of it}
As for public, that’s technically the default for your methods. In PHP 4, all properties and methods were public, meaning they could be accessed or updated in any context. When you define a method, if you just write function <methodName>([<argsList>]) {… } with nothing in front of it, it’s public. See? {show output} However, in order to have my methods look consistent, I like to place the keyword “public” in front of my public methods. {return to declaration and write ‘public’} To me, it actually looks weird to see a method declaration without one of ‘public’, ‘private’, or ‘protected’ in front of it.
As for properties, they work the same way. To declare a property public private or protected, just put the desired keyword in front of its declaration. In PHP 4, properties were always preceded with the ‘var’ keyword. To preserve backwards-compatibility, this does actually still work. It just creates a new public property. However, since this technique is deprecated, you should avoid it.
The last keyword I want to talk about in this video is, no pun intended, “final”. The final keyword is used to prevent methods from being overwritten by child classes, or to prevent a class from being extended entirely. If a child class tried to re-declare a parent class’s final method, PHP would trigger a fatal error as soon as the file containing the child class got included.
I’ll show you:
{open ParentClass class file and place ‘final’ in front of a method declaration}
Since ChildClass also defines the ‘doSomething’ method, PHP is going to complain about it:
{show output with fatal error}
This is a great tool for situations where you know that, if a child class writes its own method that your parent class has already declared, then there’s a good chance that it’ll break your functionality. Just make that property or method final and you won’t have to worry about it.
The other way you can use final is by placing it in front of a class name in the declaration. This will prevent any class from extending it. And you can see that here: {place ‘final’ in front of ‘class ParentClass’}
{show output with fatal error}
That’s all for this video.
January 22 2010 | Schmategories | Comments Off on Public, private, or protected?
To get the terminology straight, we talk about errors being “triggered”, whereas exceptions are “thrown”. The ability to throw and catch exceptions is new to PHP 5, but error handling has been around since PHP 4. In other object-oriented languages, there isn’t really a meaningful difference between errors and exceptions, but the distinction is very important in PHP. Errors can either be catchable or uncatchable, depending on how they’re triggered. Although you can trigger custom errors within your code if the need arises, errors are more commonly triggered by the parser or the PHP engine itself. Exceptions, on the other hand, are always thrown by actual PHP code, and not the underlying engine.
Let’s look at errors that can’t be caught. Parsing errors, the sort that happen when we forget to end a line with a semicolon or put one too many or few braces into our code, these aren’t going to trigger your custom handler function. The code just won’t work. In addition, errors that are thrown by the core, such as memory errors, or errors that can occur during startup, can’t be caught either. And lastly there are some errors, the ones of type ‘E_ERROR’ that just can’t be caught.
In order to handle errors, first you’ll need to create an error-handler function. The function takes 5 arguments, of which 2 are required and the rest are optional.
{show function syntax}
If you want the internal error handler to take over, for instance if your error handler is built to deal with just a few very particular cases, and based on the arguments passed, it’s been called for something different, then just return ‘false’. The internal handler will take over and execution will proceed as if your handler function weren’t there.
Here’s an example error handler:
{code sample}
The biggest change in custom error handling with PHP 5 is that you can now specify the type of error your handler function is intended to deal with, as opposed to just a catch-all for any error that a handler can deal with. This is helpful for dealing with the fact that, once you set a custom error-handler, the error_reporting setting inside php.ini will be ignored, and the custom function will be called for any reportable error type except E_STRICT. However, in PHP 6, E_STRICT will be included by default as well.
Even though the value of the error_reporting configuration isn’t checked before calling a custom error handler, you can still check the setting by calling error_reporting() with no arguments, and then have your own error handler function act appropriately based on that setting. On a related note, if the error-suppression character ‘@’ is placed at the beginning of the statement which triggered the actual error, the value of error_reporting will be 0 (or E_NONE) when checked.
Here’s a custom error_handler that takes the reporting level into consideration:
{code sample}
If you want to have an error handler that will handle any catchable errors in your code, you’ll need to set it near the beginning of your script. Up until the set_error_handler function is called, the default is the only one that gets called.
Let’s look at how this actually works. The following code will trigger an error because … … With the default error handler, the script will output this fairly unhelpful message {show broken page}.
Now, if we instead register this custom error handler function we looked at before
{show code example}
what we get instead is {show helpful error report}
A handy corollary to creating a custom error-handler function is the ability to trigger your own errors in your code. This capability is far less important in PHP 5 with the advent of exception-handling, but it’s still worth looking at.
The syntax is very simple. You just call ‘trigger_error’ with a message and, optionally, an error level. By default, it uses ‘E_USER_NOTICE’.
Here’s the previous example, but using ‘trigger_error’ instead of causing an error normally.
{code sample}
{show output}
Now, if you use exceptions in your code, and somehow have an exception that isn’t caught in a catch block somewhere, this also causes a catchable fatal error. However, rather than rely on setting a custom error handler, since exceptions provide different, and potentially useful debugging information, PHP allows you to set a custom exception handler that only gets called when an exception goes uncaught.
It has a pretty similar syntax to set_error_handler, except that the exception-handler function takes different arguments. Here’s how the function syntax is defined:
{code sample}
And here’s an example of using the custom handler to deal with an uncaught exception:
{code sample}
{show output}
January 16 2010 | Schmategories | Comments Off on Creating a custom error handler in PHP
Code is great, but comments are better. If code is what tells a computer what to do, then comments are how you communicate your intent. If the logic for a function is very clearly communicated in the comments, it can be translated by another programmer into any other programming language. If a piece of code is well-commented throughout, then even without knowing all there is to know about the language or the rest of the classes being accessed at any given point, you can figure out what the code is doing. When you need to bring a new developer up to speed on your project, a huge factor in how quickly they’ll become useful is how well your project is commented.
I’m going to assume that you’re already familiar with how to create a comment, so this video is going to focus more on what and where to comment.
Probably the first and most important thing to comment are your functions and methods. These comments can significantly illuminate your API, and that can make it easier to find and re-use existing code or bring new developers up to speed.
PHP has an excellent support community dedicated to it, and out of that community came phpDocumentor – a handy free tool that will take your project and automatically generate an API for you. It will use your comments to flesh out that API, but only if you use a style of commenting known as “javadoc” or “doc-block”. Even without using this tool however, it’s a great convention to follow. Zend Studio, which I use for my own coding environment, automatically recognizes this style of comments and will assist in their creation.
The basic syntax of javadoc looks like this: {show prepared code segment with comment}
Notice that the first line contains a slash followed by 2 asterisks, and each line starts with an asterisk. The description of whatever is being commented is the first thing in the block. After that, you can use tags preceded by @ symbols to provide very specific information that programs such as phpDocumentor use.
There are a limited number of elements where phpDocumentor looks for and parses javadoc-style comments. I suggest you make a habit of placing these comments at the top of all of them. These include files, functions, defines and includes, as well as any global variables. And assuming your project is object-oriented, you should also place these comments above your class definitions, their methods, and their properties.
When documenting a function, as is the case here, your most important tags are ‘@param’ and ‘@return’. ‘@param’ tells the name and expected value type for each variable passed to the function (this information can also be gleaned to some extent from type-hinting, but not as broadly since as of PHP 5 type-hinting only includes null, array, and object types). ‘@return’ provides information about the type of value returned. In addition to those two, if your method can throw an exception, you should include a tag for ‘@throws’ for every type of exception your function might throw – the syntax is “@throws ExceptionType – conditions which will cause this exception to be thrown”.
Now in addition to those tags, javadoc officially recognizes many more. I won’t discuss all of them – there’s an exhaustive tutorial available online that I’ll point you to in a moment. But I will take you through the ones I find most helpful most often.
To reference another method elsewhere in your code, you can use ‘@see’. And in phpDocumentor this is really great, because if it recognizes what you’re linking to, it will actually create a hyperlink to the documentation of that other portion of your code. So for instance ‘@see GoToClass’ would create a link to the documentation for a class called ‘GoToClass’ if one exists in your project. And of course, it’s useful even if you don’t use phpDocumentor because it lets your reader know what other portions of the code use or are used by the thing you’re documenting.
When a project has lots of authors, it’s a very good idea to include a tag ‘@author’ in each of your contributions. Later, if someone has a question about how it works, they can see who wrote it and ask them to explain it.
At the beginning of each file, you can place a javadoc comment as well. In the automatically generated documentation, file or page-level comments have its own section. When you use it, you must include the ‘@package’ tag. The value in @package will specify a particular group of files that all relate to one another, and all appear within the navigation generated by the documentor for that package.
When you have to stop working on something before it’s finished, there’s a tag for that too. Use ‘@todo’ followed by a description of what still has to be written.
There are currently about 30 different tags recognized by phpDocumentor, and most other javadoc parsers will recognize them as well. You can learn about all of them by going to the phpdoc manual online.
Javadoc comments placed above your files, classes, functions, methods, and properties will really liven up your API if you generate one. And even if you don’t it’s going to make your code much easier to understand. But the other important places to comment are anytime you do something where simply looking at the code, it would be difficult to figure out what’s going on. As a general guide, if you call a function defined elsewhere, include a short comment about what that function should do. That way, the person trying to work on it doesn’t need to go and hunt down its definition in a separate file. The same is true if you invoke one of the more obscure PHP functions. And if you simply need to perform a task that requires some tricky logic, or is unlike the way things are done elsewhere in the project, write a short comment explaining what you did.
Personally, I find the best way to write my scripts is to start by outlining my logic within comments before I ever write my code. Then, I just place my code within the lines of logic where I’ve described what needs to happen. It helps me ensure my logic is good before I even start the actual coding, and when I’m done, I just leave the outline there for documentation.
December 08 2009 | Schmategories | Comments Off on A primer on good code commenting
I work full-time now, and haven’t felt the need to update my portfolio regularly. That doesn’t mean I’ve forgotten it’s here – I do keep the hosting and domain registration fees paid. I just haven’t had a specific use for this blog for some time now.
However, that’s changed now. I’m very pleased to announce that I have a contract to create a series of advanced PHP video tutorials, and have been given a sufficiently flexible timeline that it shouldn’t interfere with my regular job.
Because of the NDA I signed, I can’t actually reveal what company I’m working with, but once the tutorial is finished and available for purchase, I will be promoting it here.
Now as far as the tie-in with the blog, I’ve decided that I’m going to share my research for each video by creating corresponding blog entries. The blog posts won’t include the videos themselves, but they will form the basis of the scripts I’ll use when I create them.
In time, there should be a lot of useful information on a variety of topics. Hopefully my visitors will find some of the articles useful, and may even be able to correct me if I make an error now and then.
It’s been a long time since I’ve had to research and write anything on that kind of schedule, and that’s in addition to my responsibilities at work and to my family. But I think I can handle it, because becoming a published author has been a dream of mine for a long time now, and nothing is so easy as doing work you love. Wish me luck!
October 12 2009 | Schmategories | Comments Off on New project and new direction
This was a cool little application I devised after one of my clients explained that he wanted the ability to have users upload a photo and have it automatically fit into a particular size.
Now, my first reaction could have been to simply use ImageMagick or the GD Library to simply create a thumbnail, but I’ve done that in the past and seen it stretch images in unexpected ways. He knew exactly the size he’d want his images resized to, and I didn’t want to force the users to submit pictures with a particular aspect ratio.
So, the solution I came up with, and am still pretty proud of, is a photo-cropper and resizer in one. It lets the user upload a photo, and then zoom in to a particular portion, crop it, and use it as their submission to the website. It uses javascript (jQuery flavor) to mimic the effect of selecting the target area, and then PHP on the backend does the actual resizing.
Try it out below. Your actual-size final result will appear beneath the button here on the screen. Due to limitations imposed by my server host however, large photos may not work. It wasn’t an issue for my client, since he has the luxury of a dedicated machine.
Download the source
(222 KB compressed with related graphics and script libraries)
October 21 2008 | Schmategories | Comments Off on JQuery-UI Photo Cropping Tool
Harrisonburg Blogs represents my first attempt at running a WordPress MU site. The intention is to create a portal where anyone living in or around my home city of Harrisonburg can enter into the blogging scene and easily connect with other bloggers who are already active. To that end, it will serve both as a blogging platform as well as a blog feed aggregator. The idea isn’t really original, and I freely admit that it’s mostly inspired (“stolen” being such an ugly word) by my experience with a website called chattablogs, which a friend of mine from college put together.
The fun thing about this is that I can get lots of ideas for new development tasks in order to take WordPress way beyond it’s typical capabilities. So far I’ve added in local news feeds, links to the most recent posts and comments sitewide, an ajax-based online poll, and I’ve developed a few new plugins to work both on the home page as well as the various hosted blogs. I’ve also been researching plugins written by others that I can tie in as well. So far my favorite is one called “Weather Icon,” which I use to show the current weather conditions in Harrisonburg.
What I most need now, in order to continue developing it further, are a few alpha testers who can help me find any bugs, suggest and test themes and plugins, and help turn my lone-wolf project into a true community effort. Chattablogs has become a treasure to the now-vibrant blogging scene in Chattanooga, and I’d just love to see the same thing happen here in my new hometown.
By the way, if you live in Harrisonburg, have some familiarity with WordPress, and would like to be an alpha tester, visit this page.
April 01 2008 | Schmategories | Comments Off on Harrisonburg Blogs
Why am I starting a blog called “Hire Mason Wolf”? Well, I guess the simple answer is that I would like someone to hire me, and my name is Mason Wolf. Simple enough.
Currently I’m a web developer, and I really like doing it. In past careers I’ve been a teacher, a salesperson, a dishwasher, and a lab tech, plus numerous others. Each job had its pros and cons, but I’ve found that I enjoy the current one more than I liked any of the others. So, I’ve made it my goal to get really good at doing it. Hopefully future entries will show that I’m well on my way.
Having a blog will enable me to easily showcase my work and give prospective employers some sense of who I am before they ever contact me about an interview. Plus, by having a blog I can invite passersby to leave a comment if they happen to know something that might be useful to me. And just maybe I’ll be able to contribute something worthwhile for others to read.
I don’t expect this to be a particularly active blog. I’m going to spend the first few days putting together my portfolio and then after that making only infrequent updates as I happen to finish something new to showcase or when I get a new certification worth mentioning.
My fondest wish is to see this blog be short-lived. I want a new job, and once I’ve got one, I won’t have much use for this blog anymore.
August 20 2007 | Schmategories | Comments Off on Raison D'etre