Software Development

PHP for ASP.NET Developers (part 5 – Object lifetime)

Following from my last post on the basics of object orientation in PHP, what about object lifetimes. How long does an object hang around for?

Class Diagram

In PHP you have a __destruct method on a class. This is like the finaliser in C#. For example, here is a HomoSapien class (a natural extension from the object model above).

class HomoSapien extends Mammal {

    public function __construct()
    {
        echo("Hello World!");
    }

    public function __destruct()
    {
        echo("Goodbye, cruel world!");
    }

    public function Vocalise()
    {
        echo "To be, or not to be...";
    }
}

When an object is create the __construct function is run (as we saw in the last post). The __destruct function is run when the object is unset, like this:

$human = new HomoSapien();
echo("n");
unset($human);
echo("n");

The output shows that the __constuct and __destruct methods were run.

Like the __construct function, the __destruct function does not automatically call the parent (as it would in C#). You have to do that explicitly with code like this:

public function __destruct()
{
    parent::__destruct();
}

Similarly, when the object goes out of scope the __destruct method is run:

function doStuff()
{
    $human = new HomoSapien();
    echo("n");
    $human->Vocalise();
    echo("n");
}

doStuff();

outputs:

Hello World!
To be, or not to be...
Goodbye, cruel world!

The destructor will also be run at the end of a script, so if the objects have not yet gone out of scope by that point they will be run. Any statements that output to the page will be run after the page has rendered. For example, the following script:

<html>
 <head><title>My little test PHP script</title></head>
 <body>
  <pre>
<?php

include_once('HomoSapien.php');

$theMother = new HomoSapien("Caitlin", null, null);
$theFather = new HomoSapien("Iain", null, null);

$theChild = new HomoSapien("Douglas", $theMother, $theFather);

?>
</pre></body></html>

Outputs the following:

<html>
    <head><title>My little test PHP script</title></head>
    <body>
  <pre>
Hello, I'm Caitlin!
Hello, I'm Iain!
Hello, I'm Douglas!
</pre></body></html>Douglas is no longer in the building!
Iain is no longer in the building!
Caitlin is no longer in the building!

And for completeness, here is the HomoSapien.php mentioned in the last example:

<?php
include_once("Mammal.php");

class HomoSapien extends Mammal {
    private $name;

    public function __construct($name, $mother, $father)
    {
        parent::__construct($mother, $father);
        $this->name = $name;
        echo("Hello, I'm {$this->name}!n");
    }

    public function __destruct()
    {
        echo("{$this->name} is no longer in the building!n");
    }

    public function Vocalise()
    {
        echo "I think, therefore I am.n";
    }
}
?>

Mammal.php:

<?php

include_once('Animal.php');

abstract class Mammal extends Animal {
    protected $mother;
    protected $father;

    public function __construct($mother, $father)
    {
        $this->mother = $mother;
        $this->father = $father;
    }

    public function displayParents()
    {
        echo ("Mother=".$this->mother."; Father=".$this->father);
    }
}
?>

Animal.php:

<?php

abstract class Animal {
    public abstract function Vocalise();
}

?>
Software Development

PHP for ASP.NET developers (part 4 – Object Orientation)

Continuing on my series of getting to know PHP for ASP.NET developers, I’m going to concentrate on the object oriented parts of the language.

Class Diagram

In order to creating a class is very similar to C#, for example:

class Animal {
    //put your code here
}

To create a derived class you “extend” the base class.

class Mammal extends Animal {
    //put your code here
}

There is a bit of a clash of nomenclature here, but in PHP “properties” are what C# calls “fields”. Don’t confuse PHP properties with C# properties, they are not the same thing.

To create a PHP property, all you need to do is indicate the accessibility of the property and name the property. In PHP you don’t need to declare a type as you would in C#. The accessors are public, protected and private which are similar to C#.

class Dog extends Mammal{
    protected $name;
}

You can also set default values for properties. They must be compile time constants or literal values. For example:

class Dog extends Mammal{
    private $name = "Rover";
}

To create methods (or rather “functions”) on a class you can declare them in a similar way to C#, you indicated the accessibility (although in PHP they are public by default). For example:

public function speak() {
    echo ("Woof!");
}

You can create an instance of the class in a similar way to C#, to use the methods you replace the dot in C# with a -> in PHP. For example:

$dog = new Dog();
$dog->speak();

Each class has a default constructor, to create your own constructor create a function called __construct with the desired parameters. For example:

class Mammal extends Animal {
    protected $mother;
    protected $father;

    public function __construct($mother, $father)
    {
        $this->mother = $mother;
        $this->father = $father;
    }

    public function displayParents()
    {
        echo ("Mother=".$this->mother."; Father=".$this->father);
    }
}

In derived classes you have to call the base constructor explicitly. It won’t be called otherwise. You can do this like so:

class Cat extends Mammal {
    public function __construct($mother, $father)
    {
        parent::__construct($mother, $father);
    }

PHP also supports abstract classes and methods (functions). For example, in the examples I’m using here, you probably would not want to instantiate the Animal class. Let’s also say that we want to create an abstract function (one that we fill in the details of in a derived class). Simply add the keyword “abstract” to the method signature just like in C#. For example:

abstract class Animal {
    public abstract function Vocalise();
}

abstract class Mammal extends Animal {
}

class Dog extends Mammal{

    public function Vocalise() {
        echo ("Woof!");
    }
}
Software Development

PHP for ASP.NET developers (part 3)

Now that the basics have been covered in the previous two posts, I’ll continue with some thing a bit more useful… writing some logic.

Conditional Statements

In PHP the conditional operators are pretty much the same as in C#, however there are some subtle differences.

== and != use type coercion. That means that if the type on the left side is not the same as the type on the right side then PHP will coerce them so that they can be compared. For example:

$a = 1;
$b = 1.0;

if ($a == $b)
    echo 'a and b are equal.';
else
    echo 'a and b are not equal.';

It even works if one of them is a string representation of the number one.


To get the functionality you’d expect in C# you need to use === and !==.

There is also an additional not equals operator similar to == that consists of a left and right cheveron: <>

Be careful of accidentally using a single equal sign for comparison. In C# the compiler will issue an error if it doesn’t evaluate to a Boolean. However, in PHP everything can be evaluated as a Boolean (see the section on Booleans in my previous post).

You can join comparisons together with && or || just like in C#, however, PHP also supports the use of and or or.

if statements also support an elseif clause in PHP.

if ($a < 123)
{
    // Do stuff
}
elseif ($a == 123)
{
    // Do other stuff
}
else
{
    // Do different stuff
}

Unlike C#, switch statements allow one case clause to drop in to the next, so it does not require a break at the end of each case block. The break on the last case or default is not necessary either.

switch($a)
{
    case 1:
        // Do some stuff
        break;
    case 2:
        // Do stuff
    case 3:
        // Do stuff (and continue case 2 if necessary)
        break;
    default:
        // Do stuff for all other cases
        break;
}

Loops

PHP, like C#, has a number of loop statements depending on what you want to do.

for loops, while, and dowhile work exactly the same way. So I won’t discuss them further.

Just like C#, you can break out of a loop, and continue to the next iteration of the loop.

Software Development

PHP for ASP.NET Developers (part 2)

In my previous post on PHP for ASP.NET Developers, I introduced the basics of how to set up a PHP environment and started showing the differences between PHP’s way of doing things from an ASP.NET developer’s perspective. In this post, I’m continuing with those differences.

Comments

Comments in PHP are very similar to C#. You can use /* to open a comment block and */ to close it later, and you can use the // format to comment to the end of a line.

PHP also allows the use of a hash symbol, #, to indicate that the remainder of the line is a comment.

Types

Booleans

In .NET a Boolean is a specific type and you had to get the type you are using into the Boolean to use it as such. In PHP things are a little more flexible. A Boolean can be true or false, as you might expect. But there are special cases with other types. For example, a string can be treaded as a Boolean (in an if statement, for example). If the string is empty or contains just “0” (zero) then it is treated a false. Any other value is true. Numbers have a similar effect. Zeros are treated as false and others are treated as true. null is also treated as false.

 

Dates

There are two ways to get the current date. The first is with a call to time() which returns a Unix timestamp (an integer representing the number of seconds between 00:00:00 on 1/1/1970 and the date in question). The other way is to use date() with just a format string which returns the current date formatted as specified. You can also call date and pass a timestamp and have it convert the timestamp in to the specified format. For example:

$nowTimestamp = time();
echo "<p>The time now is ".$nowTimestamp."</p>";

$nowDate = date('d/M/Y H:i:s');
echo "<p>The time now is ".$nowDate."</p>";

You can find the details of the formatting specifiers at php.net.

If you want to convert a specific date into a timestamp then you can use the function strtotime() to perform the conversion. It is quite powerful in ways that I didn’t expect, you can set the string to values such as “next Tuesday” and “yesterday”. However, the parsing of specific dates can be tricky. If you are using the American format which puts the month first you separate the components with a slash, if you are going for the European sequence which puts the day firsr then the month, you must use a dash as a separator.

For example:

$weddingTimestamp = strtotime('13-4-2012');
echo "<p>My wedding is ".$weddingTimestamp."</p>";

$weddingDate = date('d/M/Y', $weddingTimestamp);
echo "<p>My wedding is ".$weddingDate."</p>";

There is a DateTime class also available which can be used.

$now = new DateTime();
echo "<p>Today is ".$now->format('d-M-Y')."</p>";

Collections (arrays, lists, dictionaries, etc.)

PHP allows you to create an array simply by referencing the first item.

$myArray[0] = "Hello";
$myArray[1] = "World!";
echo $myArray[0].' '.$myArray[1];

And if you don’t want to have to keep a count and just keep appending on the end, you can do this:

$cities[] = 'Edinburgh';
$cities[] = 'Glasgow';
$cities[] = 'Aberdeen';
$cities[] = 'Dundee';
$cities[] = 'Inverness';
$cities[] = "Stirling";

Or, in an even more compact manner, like this:

$cities = array('Edinburgh', 'Glasgow', 'Aberdeen',
    'Dundee', 'Inverness', 'Stirling');

However, there is much more flexibility here. You can define the contents of a Dictionary like collection in the same way. Like this:

$capitals['Scotland'] = 'Edinburgh';
$capitals['England'] = 'London';
$capitals['Wales'] = 'Cardiff';
echo 'Scotland's capital is '.$capitals['Scotland'];

Like regular arrays, there is a compact way of expressing this too.

$capitals = array('Scotland' => 'Edinburgh',
    'England' => 'London', 'Wales' => 'Cardiff');

You can also use the formatting options that defining a string with double quotes permits in order to put the value of an array element into a string. Like this:

$capitals = array('Scotland' => 'Edinburgh',
    'England' => 'London', 'Wales' => 'Cardiff');
echo "The capital of Wales is {$capitals['Wales']}";

Finally, to remove an item from the array you can use the unset

unset($capitals['England']);

However, be aware that the indexes don’t move up if you remove an element, so for example, the following will fail:

$stuff = array('Zero','One', 'Two', 'Three', 'Four');
unset($stuff[1]);
echo 'Element 1 = '.$stuff[1];
Software Development

PHP for ASP.NET Developers (part 1)

For some reason that I can’t even explain to myself, I decided it would be a good idea to learn PHP. It is apparently used on roughly 60% of web sites, so it is certainly popular.

Quick Start – Install XAMPP

To get going quickly I downloaded XAMPP, which is an installation that contains all the bits I’d likely want to use to get started with. It contains apache, php and mysql in one handy package that is easier to install than trying to get the bits going separately. It also hopefully reduces the frustration of getting going which can be terribly off putting for someone new to a technology.

If you have IIS running already on your machine, I’d turn it off if you are installing XAMPP (at least during the installation and configuration phase) as the two technologies will request use of port 80 (HTTP). If you do want to run both at the same time, you are going to have to ensure that they use different ports.

if you have IIS running when XAMPP installs, then it won’t start Apache, and the use interface control panel that it provides doesn’t seem to keep up with the running state effectively so if you turn off IIS then ask it to start Apache it appears not to do so (although it does also put little warning messages up saying that if you are running 64bit to disregard the previous warning…. and I am running 64bit) yet it will serve pages.

Anyway, I didn’t install XAMPP to prepare production ready code, I installed it to learn, so I’m going to ignore some of these little foibles. Over the course of time I expect to become familiar enough with Apache, PHP, and MySQL that I’ll understand how to install them properly so that it can be used in a production setting.

Choosing an IDE

There are many IDEs to choose from, or you can go with notepad if you like. I’d rather not be stuck with notepad so I installed NetBeans 7. I don’t think it is necessarily the best, but it is a good starter. If you want a quick comparison then you can find a PHP IDE comparison chart on smashingmagazine.com.

Some basic differences between PHP and ASP.NET

Code Render Blocks

In ASP.NET you can open code render blocks using <% and close them with %> In PHP you can start with <?php and end with ?>. Some implementations also allow a shorter version of the opening tag which is <?

 

Statements

PHP statements are case insensitive, although variable names are not. For example, the following two lines are equal:

echo "<p>Hello World!</p>";
Echo "<p>Hello World!</p>";

 

Variables

In PHP all variables start with a $ sign. While statements in PHP are case insensitive, variables are not. Also, you don’t have to declare a variable with a specific type, you can just assign directly to it. You can also assign a value of a different type to the variable from the one it started out with.

However, if you do attempt to use a variable that is unassigned then you may end up with a message like this on your page:

Notice:  Undefined variable: name in C:devindex.php on line 11

If you have a variable that you no longer want, you can explicitly unset it, which means the variable will cease to exist. To unset a variable use:

unset($variable);

You can, of course, also set the variable to null. In this case the variable will still exist, it just won’t have a value.

You can check to see if a variable is set (exists and is not null) using isset($myVariable). If the variable has never been assigned, or is null, then it will return false.

 

Strings

Strings can span lines (in C#, you have to prefix the string with an @ to allow this). For example:

echo "<p>Hello World!</p>";
echo "<p>Hello
   World!</p>";

Will produce output that looks like this

<p>Hello World!</p><p>Hello
   World!</p>

Strings are handled differently if you enclose them in single or double quotes. If you enclose a string in single quotes it is treated as a literal string. If you enclose a string in double quotes, then you can embed variable any they’ll be parsed into the string…. so you can treat is like a simple form of string formatting.

If you want to put something in a string that looks like a variable name then you have to escape the initial $ sign at the front. For example:

$name = "Colin";
$message = "$name is a variable";
echo "<p>The first char is not a $ but a ",$message[0],"</p>";
echo "<p>",$message,"</p>";

If you have an exceptionally long string PHP has a neat little trick to allow you to specify a string of, I guess, limitless length. It is called a “heredoc”. How you use it is that you put in three left pointing chevrons followed by a string that denotes the end of the heredoc. That terminator string is something that will never appear in the heredoc and therefore will be safe to use as a terminator. For example:

$myString = <<<ThisIsMyTerminator
I can put as much as I want in this space
using any formatting I want, so long as I never
put in the termination sequence I specified at
the start until I am ready to terminate the
string. Like this
ThisIsMyTerminator;

Remember that you have include the semi-colon, just because the heredoc allows you to suspend all the other PHP parsing rules doesn’t mean the statement can live without its semi-colon at the end.

 

Variable variables – Or pointers to variables

PHP has a concept of Variable variables… Which is a variable that contains the name of another variable. It is a bit like a pointer to the actual variable you want to use. So, you can do this:

$myVar = "name";
$$myVar = "Colin";
echo "<p>$myVar is ",$myVar,"</p>";
echo "<p>$$myVar is ",$$myVar,"</p>";

Note that to dereference the “pointer” you use a double $ sign in front of the variable name that points to the actual value.

The result of the above is:

$myVar is name
$$myVar is Colin

If you want to get the value being pointed formatted into a string, you need to put the pointer name in braces, like this:

$myVar = "name";
$$myVar = "Colin";
echo "<p>$myVar is $myVar</p>";
echo "<p>$$myVar is ${$myVar}</p>";

 

Constants

To declare a constant in PHP there is a define statement. For example:

define(“copyright”, 2012);

Unlike variables you don’t need the $ sign in front when using the constant, however, you can’t put the constant in to strings like you can with variables.

define("year", 2012);
define("holder", "Colin Angus Mackay");
echo "<p>Copyright &copy; ",year, " ", holder, ". All Rights Reserved.</p>";