Classes, static properties, and inheritance in Coffeescript

I fear the documentation for coffeescript does not really explain the way that static and instance members work terribly well. So, I’ve put together this rough guide to classes in coffeescript

For this set of examples, I’m going to use my standard class diagram that you may have seen on other blog posts:

Creating a class

To create a class you simply write

class Animal

However, the way coffeescript works is that class will only be accessible to other things in that script. The command line utility does allow lots of files to be joined together so that may not be such an issue for the most part. However, if you want your class accessible on the page you are going to have to make it globally available in which case you will need to attach it to the window, like this:

class window.Animal

The class constructor

At its simplest the constructor can be as simple as this:

class Animal
  constructor: ->

The above construct takes no arguments and doesn’t do anything. There is no body. Note, that since coffeescript has significant white-space the constructor method has to be indented. To ensure that it is empty, don’t put the next line of code in at a greater indent depth that the word “constructor”

If the constructor doesn’t need to do anything you can leave it out. If you do need to initialise things then you can. For example, let’s say we want each animal to know its date of birth, we can do this

class Animal
  constructor: (dateOfBirth) ->
    @born = dateOfBirth

The @ symbol is a shorthand for this. However, there is an even quicker way of doing this. If your argument is simply going to be assigned to an instance variable, then you could do this instead:

class Animal
  constructor: (@born) ->

Static members

This is one area I find somewhat confusing. If you want to declare a static field on a class, you prefix it with the @ symbol, as if you are creating a short hand for this. Which is, in fact, what you are doing.

class Animal
  @population : 0

In the context of the class, the use of this is correct. You are operating int he context of an object of type class. Not an object of an instance of that class. If that makes sense. Essentially, the class itself is an object.

So, if you want to use this static variable on the class you could do something like this

class Animal
  @population : 0

  constructor: (@born) ->
    Animal.population += 1

And from outside the class, you similarly reference the class itself. For example:

(new Animal 'Today') for count in [1..10]
currentPopulation = Animal.population

Similarly, static methods on the class are prefixed with the @ symbol. For example

  @resetPopulation: () ->
    Animal.population = 0

And called on the class, rather than an instance. Also remember that if the method has no parameters, you need to include the parenthesis in the call, otherwise it gets itself in a bit of a twist. e.g.

Animal.resetPopulation()

Inheritance

To inherit from a class you simply extend the base class. For example:

class Mammal extends Animal

If your base class has a constructor then it will be called automatically when you instantiate the derived class. However, if you need to add a constructor of your own to the derived class you must remember to call the base constructor manually otherwise the base construction won’t happen as you expect.

class Animal
  @population : 0

  constructor: (@born) ->
    Animal.population += 1
    @isMulticellular = "no"
    console.log 'Animal constructor called. Population is '+Animal.population

class Mammal extends Animal
  constructor: (born) ->
    super(born)
    @isMulticellular = "yes"
    console.log 'Mammal constructor called.'

If you note, the call to super (to call the base constructor) happens first. This is generally what happens in many object oriented languages when constructing classes that have inheritance. The base parts of the class are constructed first. This gives the derived class access to the fully constructed base parts before it does its part. However, you are free to put the call to super anywhere in the derived class’s constructor.

Loading coffeescript unit tests from separate files

In my previous post I showed how to create unit tests for coffeescript. I also included a link to Eli Thompson’s coffeescript unit testing runner which allows you to easily gather all the .coffee files and the unit tests together in one place thus allowing you to keep your unit tests in separate files (rather than in-lining it in the test-runner as I showed in my previous example).

So far, so good. However, you cannot run this from the local file system as the browser’s security will complain (see the console panel in the screenshot below). The files are loaded using jQuery’s get method.

So, in order to get it to run you need to run it from within the context of a web server. You can use IIS if you are running windows, however for this example, I’m using Linux so I’ll use Apache.

Getting Apache up and running on Linux

To install Apache, in a terminal type:

sudo apt-get install apache2

By default, the newly installed server will serve from the /var/www/ which will contain an index.html already.

In order to create a new site that points to your development environment so that you can run the unit tests locally you need to modify apache.

Start by opening the /etc/apache2/apache2.conf file. (You’ll need to use sudo or run as root in order to write this back as your user won’t have the permission by default.) And add the following to the end of the file:

NameVirtualHost 127.0.0.1:80

This tells Apache that you’ll be creating named web sites on the IP/port specified. This is most useful if you have a server that hosts multiple sites. In our case we are simply using it to create a development site on our local machine. Because we’ve specified the loopback address it won’t be visible outside of the machine it is running on. (More info on NameVirtualHost)

Next we have to create a file in /etc/apache2/sites-available/ directory. As far as I can see, the convention is to use the host name as the name of the file. So a site running a www.example.com would have a file of the same name. In this case, as it is a development site running only on localhost I like to name it something along the lines of myproject-localhost so that it is obvious that it is running on the loop back address.

For this example, I’ll create a file called /etc/apache2/sites-available/coffee-tests-localhost with the following content:

<VirtualHost 127.0.0.1:80>
ServerName coffee-tests-localhost
ServerAlias www.coffee-tests-localhost
ServerAdmin colin.mackay@example.com
DocumentRoot /home/colinmackay/hg/blog-and-demos/three-of-a-kind
</VirtualHost>

Since this file is in sites-available that means it is not yet enabled, so the server won’t be serving it up. In order to get it served up there needs to be a duplicate in /etc/apache2/sites-enabled/. You don’t need to create a duplicate in Linux as you can create a symbolic link to the original file. To do that, type the following at a terminal:

cd /etc/apache2/sites-enabled/
sudo ln -s ../sites-available/coffee-tests-localhost .

(Note the dot at the end of the second line!)

Since the host name does not really exist, no DNS will resolve it, this is the point that you need to edit the /etc/hosts file so that your local browser can go to the web site. Add the following line to the hosts file:

127.0.0.1     coffee-tests-localhost

Finally restart the Apache server:

sudo /etc/init.d/apache2 restart

You should now have your web site up and running and displaying the tests to you now.

The running tests

When we go to http://coffee-tests-localhost/tests/test-runner.htmlall the tests now run and there is no error in the browser’s console:

More information

Unit testing with Coffeescript

I’ve recently started  looking at Coffeescript. And to get going with that I’m jumping directly in with unit-testing. I figured that it would be an interesting way to learn the language.

Since coffeescript compiles to javascript, you can use a javascript unit testing framework such as QUnit which can be downloaded from github.

Getting to grips with QUnit

Before we delve into coffeescript part, let’s have a very quick look at QUnit.

In order to run unit tests create an HTML page that will contain the runner. In this page you need to include jQuery, and QUnit (http://code.jquery.com/qunit/git/qunit.css and http://code.jquery.com/qunit/git/qunit.js). The body of your test runner needs to contain elements that QUnit will update during the tests. You also need to include the tests themselves.

I won’t go much further in to QUnit as there is already ample
information about getting going with QUnit over on the jQuery website.

Running coffeescript in the browser

Normally coffeescript is pre-compiled into javascript before being sent to the browser, however it is possible to have the browser compile coffeescript itself. This would not be recommended for production code, but does make life easier for running unit tests as the browser handles the compilation step for you.

You can run coffeescript in the browser by using the script located at http://jashkenas.github.com/coffee-script/extras/coffee-script.js. Then
any subsequent script blocks that are marked with the text/coffeescript type will be compiled on-the-fly. e.g.

<script type="text/coffeescript">
    // Your coffee script code here
</script>

One annoyance I’ve found is that coffeescript relies on “significant whitespace” which means that I’m forced to format my code the way coffeescript likes. In general thats not necessarily a bad thing, especially when you are editing coffeescript files, but with inline script blocks it can be irritating. Your script block may already be indented (and I tend to go for indents of two spaces for HTML files, as opposed to 4 for C#) which coffeescript doesn’t seem to like.

Running some tests

First of all this is what a test looks like in javascript using QUnit.

  <script type="text/javascript">
    $(function(){
        module("My javascript test");

        test("Assert 1 not equal 0", function(){
          ok(1!==0, "One expected to not equal zero");
        });
    });
  &lt/script>

What’s happening above is that the tests run when jQuery is ready. In other words, once the DOM is loaded. (See also: $(document).ready()).

The module method is simply a way of segregating the tests in to groups. All tests that follow a call to module will be grouped into that “module”.

The test happens in the call to test which normally takes a string which is the text to display each time the test is run, and a function containing the actual test. The second test that I have is written in coffee script.

<script type="text/coffeescript">
$(()->
    module("My coffeescript test");
    test("Assert 1 equals 1", ()-> ok(1==1, "One expected to equal one"));
);
</script>

While in coffeescript you don’t need the brackets around the function parameters, I prefer them. Nor do you need the semi-colon to terminate each statment, and again this is personal preference. You’ll see lots of coffeescript that won’t use brackets and semi-colons in the above situations.

Here is the result of the two tests above:

Test 	    runner with passing tests

In both tests above there is a call to ok which asserts that the condition passed in as the first argument is true, if not it fails the test. When a test fails the text in the second parameter of the ok function is displayed. For example, a test designed to deliberately fail:

    test("Assert 2 equals 3", () -> ok(2==3, "2 expected to equal 3"));

And the result in the test runner:

Test runner with failing test

Unit testing with .coffee files

Eli Thompson has an example of how you might want to put together unit tests for a
system written in coffeescript
. The core of his example is to define a list of coffeescript files and a list of tests and have a bit of coffeescript dynamically load them in order to run the tests.

In that example, scriptsToTest contains a list of coffeescript files that contain the code to test, and a list of tests which reference the files that contain the actual tests. The code then loads each coffeescript file, compiles it to javascript and loads it into the DOM so that the browser can execute it. The code that does all the hard work is a rather elegant 9 lines of
coffeescript (not including the declaration of the files involved).

More information

This was a very quick introduction to unit testing with QUnit and
using coffeescript. Here are links to more resources to continue
with:

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();
}

?>

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!");
    }
}

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.

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];

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>";

Tip-of-the-day: Columns in CSS

The CSS Multi-column layout module is a Candidate Recommendation that allows CSS to specify various aspects of column layout for page flow. It has some implementations in Chrome and FireFox but it does not work in IE yet. (I’ve not tested it on other browsers). Because of this you have to specify the Webkit and Mozilla extensions in the CSS. e.g.

div.example
{
  column-width: 300px;
  -moz-column-width: 300px;
  -webkit-column-width: 300px;
}

To show you what it can do, I’ve created some small simple examples using a list of cities, a poem and some prose. (The links open in new windows. You are encouraged to look at the page source too)

Without Columns With Columns

Checking for NULL using Entity Framework

Here is a curious gotcha using the Entity Framework: If you are filtering on a value that may be null then you may not be getting back the results you expect.

For example, if you do something like this:

var result = context.GarmentsTryOns
    .Where(gto => gto.WeddingId == weddingId
                  && gto.PersonId == personId);

And personId is null then you won’t get any results back. This is because under the hood the query is structured like this:

…WHERE WeddingId = @p0 AND PersonId = @p1

That’s all great when @p1 has a value, but when it is null SQL Sever says nothing matches. In SQL Server, NULL is not a value, it is the absence of a value, it does not equal to anything (including itself) e.g. Try this:

SELECT CASE WHEN NULL = NULL THEN 1 ELSE 0 END

That returns 0!

Anyway, if you want to test NULL-ability, you need the IS operator, e.g.

SELECT CASE WHEN NULL IS NULL THEN 1 ELSE 0 END

That returns 1, which is what you’d expect.

Now, for whatever reason, EF is not clever enough to realise that in the above example, personId is (perfectly validly) null in some cases and switch from using = to IS as needed. So, what we need is a little jiggery-pokery to get this to work. EF can tell if you hard code the null, so you can do this in advance to set things up:

Expression<Func<GarmentTryOns, bool>> personExpression;
if (personId == null)
    personExpression = gto => gto.PersonId == null;
else
    personExpression = gto => gto.PersonId == personId;

This can then be injected as a Where filter onto the query and it EF will interpret it correctly. Like this:

var result = context.GarmentTryOns
                      .Where(gto => gto.WeddingId == weddingId)
                      .Where(personExpression);

The SQL that EF produces now correctly uses PersonId IS NULL when appropriate.