To get started with COM, the first script to create simply fires up a COM component, and calls a function on it. The COM component we will use for this is WScript.Shell, which is a very simple COM component to get started with. "WScript", by the way, is the Windows Scripting Host; Microsoft's script management software. The various components that WSH offers us give almost unprecedented flexibility.
Here is our first script, just four lines long:
$shell = new COM("WScript.Shell");
$shell = null;
Author's Note: In PHP 4, you needed to explicitly release all references to your COM objects. This is no longer necessary in PHP. Strictly speaking, setting the objects to NULL is also not necessary, but, hey, I'm a clean freak.
You should be able to see what that script does even without running it, because the code is nice and clear. If you hadn't guessed, it simply runs Notepad on the computer where the script was executed - nothing special, given that we can just exec() in PHP to execute outside functions, but it should at least get you started thinking in terms of COM.
Note that in line one we create the COM object, $shell, by passing "Wscript.Shell", the name of the component we want to create, to the constructor of the COM class. This returns $shell, a working WScript.Shell object, on success, otherwise PHP will issue an error and return false.
In line two, the run() function of WScript.Shell is used, which runs an executable file. It is not really within the scope of this book to discuss the workings of WScript.Shell or other COM objects, but try searching Google exactly like this:
"wshshell object" msdn
Make sure you keep the quotes intact - all being well, the Microsoft Developer Network (MSDN) should be the first link, giving the full documentation for this object, as well as other related components.
Lines three and four free the COM component created on line one, then clears the variable. This might seem odd given that PHP frees its resources when it closes, however the nature of COM means that each object has a reference count that needs to be decremented when the object is no longer used - PHP does not do this, so the object sits around, unused on your server, for several minutes after your script finishes.
As a result, you should always set your objects to null - this will ensure full garbage collection. As mentioned elsewhere, it is generally smart to always do your housekeeping yourself - relying on PHP to clean up your after your script is sloppy and haphazard.
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Advanced COM >>
Previous chapter: Instantiating an object
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.