Menu

Basic class structure: properties[] and p()

Beginning with this post, we will be describing the basic structure of go!Johnny classes. As virtually each class represents an HTML element (tag), most properties and methods are common to all of them.

First of all, let's consider the properties variable. This is an array that stores all the properties (!) of the HTML element represented by the instance. You can set any property you want, and it will be communicated to the resulting HTML tag. E.g.:

<?php
$notice = new TDiv('The content of this page is in public domain.');
$notice->properties['class'] = 'centered';
$notice->properties['onclick'] = 'hidenotice()';
echo $notice;

This will output:

<div id="notice" class="centered" onclick="hidenotice()">
The content of this page is in public domain.
</div>

But there is a more convenient way to do this:

<?php
$notice = new TDiv('The content of this page is in public domain.');
$notice->p('class', 'centered');
$notice->p('onclick', 'hidenotice()');
echo $notice;

with exactly the same output as above.

That is: you can either access the properties[] array directly, or you can use the shortcut function p(). There are two advantages in using this function:

  1. it saves you some typing;
  2. you can poke an unexisting property without getting an error.

The p() function can be used both for setting a property and for getting the value of an existing property. E.g., if you add this line to the above code:

<?php
echo $notice->p('class');

you will get this output:

centered

If you try to get the value of a property that doesn't exist, you just get an empty string:

<?php
echo $notice->p('onload');

output:


Note:
In the example above, you probably noticed that an id property appeared in the HTML output. This is generated automatically from the name given to the variable containing the class instance in the php code. You can disable this behaviour by defining GJ_AUTOID as false before including the library.

Posted by panglossa 2013-04-08 Labels: property properties set get p() id

Log in to post a comment.