Archive for the 'PHP' Category

My first lesson in PHP/Wordpress plugin development

Recently I had released a WordPress plugin - Google Blog Search Preview. I had tested it over two webhosting providers and everything seemed perfect. But within a week of release, I was getting reports of this plugin failing on certain installations. Well, it turns out that I had coded my plugins in PHP5.

The error was,

Parse error: syntax error, unexpected T_STATIC, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in /home/brodopr/public_html/brodo/wp-content/plugins/jj_gblogsearch.php on line 15

Unfortunately many sites still run WordPress on PHP4. The biggest problem is that object oriented features in PHP is very different between version 4 and 5. For example, the static keyword is not available in PHP 4 which I was using in my plugins!

So the first lesson in WordPress plugin development - Test your plugins in both PHP 4 and PHP 5 installations! WAMP server even has a plugin which allows you to switch between PHP4 and PHP5. So that was easy!

I have released version 1.1 of Google Blog Search Preview  which works on PHP4 and PHP5. You can download it here. Many thanks to Carlo and Len for reporting this problem.

Wordpress Plugin - Google Blog Search Preview

I do most of my programming during weekends. This weekend I decided to write a WordPress plugin. I also wanted to improve my recently acquired PHP skills.

WordPress dashboard displays incoming links from Technorati. This is very useful since it lets you know who are discussing about your blog (not all have trackbacks enabled). But sometimes not all links are visible on Technorati. So I supplement it by doing a “link search” on Google Blog Search.

What if I display the Google Blog Search incoming links also on the WordPress dashboard? Hence this plugin! This plugin uses rss library of WordPress. I wanted to do Ajax, but there isn’t any “native” support for Ajax in WordPress :(

Do checkout Google Blog Search Preview Plugin!

PHP notes for Java programmer (4) - classes

Here is the last set of PHP notes which cover object oriented programming in PHP. The notes conclude with a set of supplementary notes. The entire list of PHP notes are available here.

PHP Notes - Object oriented programming

1. To call class methods without an instance, use scope resolution operator(::) else use (->). Check the following example,

class test {
 function f1() {
  echo “hello”;
 }
}

test::f1();

$t1 = new test();
$t1->f1();

2. In PHP, __autoload function (automatically called) can be used to simulate “import” functionality. This is very handy if you store your classes in separate PHP files. For example,

<?php
function __autoload($class_name) {
    require_once $class_name . ‘.php’;
}

$obj  = new MyClass1();
$obj2 = new MyClass2();
?>

3. PHP has constructors (__construct()) and destructors (__destruct()). There is no chaining of constructor or destructor calls. Use parent::__construct() for the same.

4. Method and properties can have “public”, “private” or “protected” visibility.

5. Use const keyword to define constants inside classes.

6. PHP has the standard class constructs - abstract, extends, interface, implements etc.

7. It is possible to overload method calls and member access using __call, __get and __set. This will be triggered only if the accessed attribute or method doesn’t exist! isset() and unset() can also be overridden using __isset() and __unset().

8. For serialization methods __sleep and __wakeup. All methods starting with __ are reserved as magic methods in PHP!

9. To perform shallow copy, use clone directive. It is also possible to define a __clone() method.

10. PHP supports reflection paradigm. For more details, checkout http://www.php.net/manual/en/language.oop5.reflection.php

11. PHP supports type hinting for object and array types. For example, function f1(array $a) { }

12. A typical PHP class declaration is shown below,

class Test extends T1 implements T2 {

 public $a;
 
 public function testmethod($value) {
  $this->a = $value;
 }
}

13. PHP exception handling is similar to Java. It is also possible to extend the base “Exception” class. Here is a sample use of exception,

try {
    $error = ‘error message’;
    throw new Exception($error);
} catch (Exception $e) {
    echo ‘Caught exception: ‘,  $e->getMessage(), “\n”;
}

PHP supplementary notes

1. For maximum security always validate user input. You don’t want to be a victim of SQL injection attack!

2. For database access, provide least access rights needed by the application.

3. On a production system it is better to disable error reporting.

PHP notes for Java programmer (3) - control structures and functions

Here is the 3rd set of PHP notes. With this all the core PHP language features are covered. The only thing left is the OOP support in PHP - classes and interfaces. For classes, I will cover only the PHP 5 features (PHP 4 has a different model). Stay tuned for the final set.

PHP Language Reference Notes - control structures and functions

1. There are two equality operators in PHP. == is for “equals” and === is for “identical”. “===” return true only if both operands are of the same type!

2. @ is an error control operator in PHP. This works only on expressions and will suppress error messages. Handy if you don’t want to expose errors to the page being displayed.

3. Backticks (“) can be used as the execution operator in PHP. for example $output = `ls`; will contain the directory listing in linux.

4. There are two types of logical operators - “and”,”&&” , “or”, “||”. The “or” operator has less precedance than “||”.

5. In arrays, “+” operator indicates union. “==” checks whether same key/pair value exist in arrays, while “===” also checks for their order (identical).

6. Following are the control structures in PHP,

if ($a > $b) {
   echo “a is bigger than b”;
} elseif ($a == $b) {
   echo “a is equal to b”;
} else {
   echo “a is smaller than b”;
}

while ($i <= 10) {
   echo $i++;
}

do {
   echo $i;
} while ($i > 0);

for ($i = 1; $i <= 10; $i++) {
   echo $i;
}

switch ($i) { // switch can work on strings!
case “apple”:
   echo “i is apple”;
   break;
case “bar”:
   echo “i is bar”;
   break;
case “cake”:
   echo “i is cake”;
   break;
}

7. There are two forms of else if in if blocks. It can be “else if” or “elseif”.

8. All control structures has an alternate form which uses colon(:) and end<type>; For example, if($a): endif;

9. PHP has a shortcut form of for, the foreach. Consider the following example,

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $value) {
   echo $value;
}
?>

10. The break statement takes an optional parameter indicating how many levels needs to be skipped. For example, break 2;

11. The continue statement takes an optional parameter indicating how many levels needs to be skipped when going to the next iteration. For example, continue 2; Also note that continue applies to switch statement as well!

12. The declare construct can be used for profiling. For example, declare(ticks=1) { //code here }. This works along with register_tick_function(). The registered function will be called for every n low level instructions, where n is the number of ticks.

13. To include another PHP file use either include() or require() construct. require() will cause a fatal error if the required file is missing. To avoid multiple includes of the same file, use include_once() or require_once().

14. In PHP, it is possible to define functions inside functions! Function visibility is global but the outer function must be called before you can call the inner function!

15. There is no function overriding or overloading in PHP.

16. Function arguments can be passed by value or reference. To pass by reference prefix variable with &. PHP also supports variable function arguments.

17. Default function argument values are possible and they should be ordered from right to left. For example,

function test($a, $b=”value”) {
}

18. PHP also has variable functions. This can be used for implementing function callbacks!

function f1() {
 echo “hello”;
}
$functionvar = “f1″;
$functionvar();

PHP notes for Java programmer (2) - types and variables

PHP Language Reference Notes - Types, Variables and Constants

1. It is not possible to mix XHTML declaration with PHP. Once way to solve this is to use <?php echo(”<?xml version=”1.0″ encoding=”UTF-8″?>\n”); ?>

2. A PHP instruction is terminated by a semicolon (except for code blocks such as an if block).

3. Three types of comments are possible - /*comment*/, //comment and #comment. Be careful when you mix them!

4. PHP supports eight basic types. They are boolean, integer, float, string, array, object, resource and NULL.

5. PHP types are weak and are dynamically typed. PHP variables are prefixed by dollar sign($).

6. Type conversion is easy! You can cast types or use settype() method. For example $intvar = (int)”100″ is a valid statement in PHP!. This is equivalent to   $v1 = “100″; settype($v1,”integer”);

7. Boolean literals true and false are case insensitive.

8. Integer overflow causes a variable change its type to float!

9. PHP has no native support for unicode strings.

10. String literals can be expressed in 3 forms - single quoted, double quoted and using heredoc syntax.

11. Single quote strings don’t evaluate the string content. Hence if variables are inside strings, they are not interpreted.

12. Double quote strings are evaluated. Hence if there are variable or special characters, the corresponding value is output. For example echo “hello $val” will print “hello world” if $val=”world”.

13. String characters can be accessed using index operation. For example, $v1[4];

14. Use complex syntax in double quoted strings for evaluating complex expressions!. For example,  $v1 = “hell”; echo “{$v1}o”; - The output is hello.

15. For string concatenation using dot(.) operator. For example “Hello”.” World”

16. By default arrays in PHP are associative in nature. Hence array(”0″,”1″,”2″) and array(”0″ => “0″, “1″ => “1″, “2″ => “2″) are identical.

17. $v1[] = “100″; extends an array by adding the element “100″ to it. The key will be maxkey + 1;

18. PHP supports callback functions.

19. PHP variable scope rules are a bit strange. A globally declared variable is not visible inside a function snippet. For example following won’t print “hello” since $a inside test() is a different variable!

<?php
$a = “hello”;
function test() {
  echo $a;
}
test();
?>

20. Keyword global can be used to refer global variables in functions. For example,

<?php
$a = “hello”;
function test() {
  global $a
  echo $a;  // prints hello
}
test();
?>

21. Another alternative is to use $GLOBALS superglobal! In the above example,  $GLOBALS[’a'] returns the value of $a.

22. Another interesting PHP variable property is that variables declared in a code block is visible below the code block! Consider the following example,

<?php
$check = true;
if($check) {
  $a = “hello”;
}
echo $a; // prints hello
?>
23. PHP has something called variable of variable. For example,  $a = “hello”; $$a = “world”; echo “$a $hello”; // This prints “hello world”.

24. In PHP, constants are declared using define. There is no need for a dollar sign to refer a constant. For example,  define(”PI”,3.14);echo PI;

25. PHP has a large number of magic constants. Values of some these depend on the context they are used. For example, echo __LINE__; will give you the current line number!

PHP notes for Java/C# programmer - set 1

Are you a Java/C# programmer looking for a crash course on PHP? Here is an easy way. In the next 5 days I will be going through the entire PHP documentation and will be taking notes which are relevant and unique to PHP.

I am a hardcore Java programmer and hence by following me you can quickly learn PHP! My notes will be mainly based on the online PHP manual. Here is the first set of PHP notes.

General PHP Notes

1. PHP - PHP:Hypertext Preprocessor is an open source general purpose scripting language.

2. PHP can be used for server side scripting, command line processing and as a GUI application (PHP-GTK).

3. PHP is changed to a proper object oriented language from version 5 onwards and allows OOP paradigm.

4. First sample program, the famous “Hello World”,

<html>
<head><title>Hello World</title></head>
<body>
<?php echo “Hello World” ?>
</body>
</html>

5. PHP exposes a set of superglobal variables accessible from anywhere. For example, $_POST superglobal can be used to extract http post parameters. $_POST is an associative array.

6. If the HTML form field name contains a dot(.), it is converted to an underscore(_) automatically by PHP. For example, if the text field name is “user.name”, you should use $_POST[”user_name”] to retrieve its value!

7. There are a couple of mailing lists available for PHP. It is at http://www.php.net/mailing-lists.php. So far I have only subscribed to “Announcements”.

Next set of PHP notes on the language features will be published tommorrow.