Tag Archives: php

Coding conventions: PHP

Code structure

Assignment expressions

Using assignment as an expression is surprising to the reader and looks like an error. Do not write code like this:

if ( $a = foo() ) {
    bar();
}

Space is cheap, and you’re a fast typist, so instead use:

$a = foo();
if ( $a ) {
    bar();
}

Using assignment in a while() clause used to be legitimate, for iteration:

$res = $dbr->query( 'SELECT * FROM some_table' );
while ( $row = $dbr->fetchObject( $res ) ) {
    showRow( $row );
}

This is unnecessary in new code; instead use:

$res = $dbr->query( 'SELECT * FROM some_table' );
foreach ( $res as $row ) {
    showRow( $row );
}

Spaces

MediaWiki favors a heavily-spaced style for optimum readability.

Put spaces on either side of binary operators, for example:

// No:
$a=$b+$c;

// Yes:
$a = $b + $c;

Put spaces next to parentheses on the inside, except where the parentheses are empty. Do not put a space following a function name.

$a = getFoo( $b );
$c = getBar();

Opinions differ as to whether control structures  if, while, for, foreach etc. should be followed by a space; the following two styles are acceptable:

// Spacey
if ( isFoo() ) {
        $a = 'foo';
}

// Not so spacey
if( isFoo() ) {
        $a = 'foo';
}

In comments there should be one space between the # or // character and the comment, and a comment should be put on its own line.

// No:
        public static function getFoo( $bar ) {
                if ( $bar !== false ) { //because this and that..
                        return $bar; //already defined, return it
                }
        }

// Yes:
        public static function getFoo( $bar ) {
                // Because this and that..
                if ( $bar !== false ) {
                        // Already defined, return it.
                        return $bar;
                }
        }

To help developers fix code with an inadequately spacey style, a tool called stylize.php has been created, which uses PHP’s tokenizer extension to enforce most whitespace conventions automatically.

Ternary operator

The ternary operator can be used profitably if the expressions are very short and obvious:

$swat = isset( $this->mParams['swat'] ) ? $this->mParams['swat'] : false;

But if you’re considering a multi-line expression with a ternary operator, please consider using an if() block instead. Remember, disk space is cheap, code readability is everything, “if” is English and ?: is not.

PHP-v5.3 shorthand

Since we still support PHP 5.2.x, use of the shorthand ternary operator (?:) introduced in PHP 5.3 is not allowed.

String literals

For simple string literals, single quotes are slightly faster for PHP to parse than double quotes. Perhaps more importantly, they are easier to type, since you don’t have to press shift. For these reasons, single quotes are preferred in cases where they are equivalent to double quotes.

However, do not be afraid of using PHP’s double-quoted string interpolation feature: $elementId = “myextension-$index”; This has slightly better performance characteristics than the equivalent using the concatenation (dot) operator, and it looks nicer too.

Heredoc-style strings are sometimes useful:

$s = <<<EOT
<div class="mw-some-class">
$boxContents
</div>
EOT;

Some authors like to use END as the ending token, which is also the name of a PHP function. This leads to IRC conversations like the following:

<Simetrical>      vim also has ridiculously good syntax highlighting.
<TimStarling>     it breaks when you write <<<END in PHP
<Simetrical>      TimStarling, but if you write <<<HTML it syntax-highlights as HTML!
<TimStarling>     I have to keep changing it to ENDS so it looks like a string again
<brion-codereview>        fix the bug in vim then!
<TimStarling>     brion-codereview: have you ever edited a vim syntax script file?
<brion-codereview>        hehehe
<TimStarling>     http://tstarling.com/stuff/php.vim
<TimStarling>     that's half of it...
<TimStarling>     here's the other half: http://tstarling.com/stuff/php-syntax.vim
<TimStarling>     1300 lines of sparsely-commented code in a vim-specific language
<TimStarling>     which turns out to depend for its operation on all kinds of subtle inter-pass effects
<werdnum> TimStarling: it looks like some franken-basic language.

Functions and parameters

Avoid passing huge numbers of parameters to functions or constructors:

//Constructor for Block.php as of 1.17. *DON'T* do this!
function __construct( $address = '', $user = 0, $by = 0, $reason = '',
        $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
        $hideName = 0, $blockEmail = 0, $allowUsertalk = 0 )
{
        ...
}

It quickly becomes impossible to remember the order of parameters, and you will inevitably end up having to hardcode all the defaults in callers just to customise a parameter at the end of the list. If you are tempted to code a function like this, consider passing an associative array of named parameters instead.

In general, using boolean parameters is discouraged in functions. In $object->getSomething( $input, true, true, false ), without looking up the documentation for MyClass::getSomething(), it is impossible to know what those parameters are meant to indicate. Much better is to either use class constants, and make a generic flag parameter:

$myResult = MyClass::getSomething( $input, MyClass::FROM_DB & MyClass::PUBLIC_ONLY );

Or to make your function accept an array of named parameters:

$myResult = MyClass::getSomething( $input, array( 'fromDB', 'publicOnly' ) );

Try not to repurpose variables over the course of a function, and avoid modifying the parameters passed to a function (unless they’re passed by reference and that’s the whole point of the function, obviously).

C borrowings

The PHP language was designed by people who love C and wanted to bring souvenirs from that language into PHP. But PHP has some important differences from C.

In C, constants are implemented as preprocessor macros and are fast. In PHP, they are implemented by doing a runtime hashtable lookup for the constant name, and are slower than just using a string literal. In most places where you would use an enum or enum-like set of macros in C, you can use string literals in PHP.

PHP has three special literals: true, false and null. Homesick C developers write null as NULL because they want to believe that it is a macro defined as ((void*)0). This is not necessary.

Use elseif not else if. They have subtly different meanings:

// This:
if( $foo == 'bar' ) {
        echo 'Hello world';
} else if( $foo == 'Bar' ) {
        echo 'Hello world';
} else if( $baz == $foo ) {
        echo 'Hello baz';
} else {
        echo 'Eh?';
}

// Is actually equivalent to:
if( $foo == 'bar' ) {
        echo 'Hello world';
} else {
        if( $foo == 'Bar' ) {
                echo 'Hello world';
        } else  {
                if( $baz == $foo ) {
                        echo 'Hello baz';
                } else {
                        echo 'Eh?';
                }
        }
}

And the latter has poorer performance.

Naming

Use lowerCamelCase when naming functions or variables. For example:

private function doSomething( $userPrefs, $editSummary )

Use UpperCamelCase when naming classes: class ImportantClass. Use uppercase with underscores for global and class constants: DB_MASTER, Revision::REV_DELETED_TEXT. Other variables are usually lowercase or lowerCamelCase; avoid using underscores in variable names.

There are also some prefixes used in different places:

Functions

  • wf (wiki functions) – top-level functions, e.g.
function wfFuncname() { ... }

Verb phrases are preferred: use getReturnText() instead of returnText().

Variables

  • $wg – global variables, e.g. $wgVersion, $wgTitle. Always use this for new globals, so that it’s easy to spot missing “global $wgFoo” declarations. In extensions, the extension name should be used as a namespace delimiter. For example, $wgAbuseFilterConditionLimit, not $wgConditionLimit.

It is common to work with an instance of the Database class; we have a naming convention for these which helps keep track of the nature of the server to which we are connected. This is of particular importance in replicated environments, such as Wikimedia and other large wikis; in development environments there is usually no difference between the two types, which can conceal subtle errors.

  • $dbw – a Database object for writing (a master connection)
  • $dbr – a Database object for non-concurrency-sensitive reading (this may be a read-only slave, slightly behind master state, so don’t ever try to write to the database with it, or get an “authoritative” answer to important queries like permissions and block status)

The following may be seen in old code but are discouraged in new code:

  • $ws – Session variables, e.g. $_SESSION[‘wsSessionName’]
  • $wc – Cookie variables, e.g. $_COOKIE[‘wcCookieName’]
  • $wp – Post variables (submitted via form fields), e.g. $wgRequest->getText( ‘wpLoginName’ )
  • $m – object member variables: $this->mPage. This is discouraged in new code, but try to stay consistent within a class.

Pitfalls

  • Understand and read the documentation for isset() and empty(). Use them only when appropriate.
    • empty() is inverted conversion to boolean with error suppression. Only use it when you really want to suppress errors. Otherwise just use !. Do not use it to test if an array is empty, unless you simultaneously want to check if the variable is unset.
    • Do not use isset() to test for null. Using isset() in this situation could introduce errors by hiding mis-spelled variable names. Instead, use $var === null
  • Study the rules for conversion to boolean. Be careful when converting strings to boolean.
  • Be careful with double-equals comparison operators. Triple-equals is often more intuitive.
    • ‘foo’ == 0 is true
    • ‘000’ == ‘0’ is true
    • ‘000’ === ‘0’ is false
  • Array plus does not renumber the keys of numerically-indexed arrays, so array(‘a’) + array(‘b’) === array(‘a’). If you want keys to be renumbered, use array_merge(): array_merge( array( ‘a’ ), array( ‘b’ ) ) == array( ‘a’, ‘b’ )
  • Make sure you have error_reporting set to E_ALL for PHP 5. This will notify you of undefined variables and other subtle gotchas that stock PHP will ignore. See also Manual:How to debug.
  • When working in a pure PHP environment, remove any trailing ?> tags. These tags often cause issues with trailing white-space and “headers already sent” error messages (cf. bugzilla:17642 and http://news.php.net/php.general/280796).
  • Do not use the ‘goto’ syntax introduced in 5.3. PHP may have introduced the feature, but that does not mean we should use it.

Comments and Documentation

The Doxygen documentation style is used (it is very similar to PHPDoc for the subset that we use). A code documentation example: giving a description of a function or method, the parameters it takes (using @param), and what the function returns (using @return), or the @ingroup or @author tags.

Use @ rather than \ as the escape character (i.e. use @param rather than \param) – both styles work in Doxygen, but for backwards and future compatibility MediaWiki uses has chosen the @param style as convention).

Use /** to begin the comments, instead of the Qt-style formatting /*!.

General format for parameters is such: @param type $varname: description. Multiple types can be listed by separating with a pipe character.

Doxygen documentation states that @param should have the same format as phpDocumentor:

@param  datatype1|datatype2 $paramname description

For every public interface (method, class, variable, whatever) you add or change, a @since tag should be provided, so people extending the code via this interface know they are breaking compatibility with older versions of the code.

class Foo {

        /**
         * @var array $bar: Description here
         * @example array( 'foo' => Bar, 'quux' => Bar, .. )
         */
        protected $bar;

        /**
         * Short decription here, following by documentation of the parameters.
         *
         * @since 1.42
         *
         * @param FooContext $context
         * @param array|string $options: Optionally pass extra options. Either a string or an array of strings.
         * @return Foo|null: New instance of Foo or null of quuxification failed.
         *
         * Some example:
         * @code
         * ...
         * @endcode
         */
        public function makeQuuxificatedFoo( FooContext $context = null, $options = array() ) {
                /* .. */
        }

}

PHPDoc was used at the very beginning but got replaced with Doxygen for performance reason. We should probably drop PHPDoc compatibility.

@var: documenting class members

There is a ‘bug’ in Doxygen which affects MediaWiki’s documentation: using @var to specify the class members’ type only works if the variable name is appended:

       /**
         * Some explanation about the variable
         *
         * @var string $msg
         */
        protected $msg;

If you don’t append the variable name Doxygen will ignore the entire comment block and it will not be included in the docs.

Integration

There are a few pieces of code in the MediaWiki codebase which are intended to be standalone and easily portable to other applications; examples include the UTF normalisation in /includes/normal and the libraries in /includes/libs. Apart from these, code should be integrated into the rest of the MediaWiki environment, and should allow other areas of the codebase to integrate with it in return.

Global objects

Do not access the PHP superglobals $_GET, $_POST, etc, directly; use $request->get*( ‘param’ ) instead; there are various functions depending on what type of value you want. You can get a WebRequest from the nearest RequestContext, or if absolutely necessary $wgRequest. Equally, do not access $_SERVER directly; use $request->getIP() if you want to get the IP address of the current user.

Static methods and properties

Static methods and properties are useful for programmers because they act like globals without polluting the global namespace. However, they make subclassing and reuse more difficult for other developers. Generally, you should avoid introducing static functions and properties when you can, especially if the sole purpose is to just save typing.

For example, lots of developers would prefer to write something like:

Foo::bar();

This is because it is shorter and takes less keystrokes. However, by doing this you’ve made the Foo class much harder to subclass and reuse. Instead of introducing a static method, you could just type:

$f = new Foo();
$f->bar();

Remember, shorter does not always mean better, and you should take the time to design your classes in a way that makes them easy to reuse.

Late static binding

In PHP 5.3, a new feature called “Late Static Binding” (LSB) was added to help work around this perceived lack of functionality in static functions. However, the usefulness of LSB is debatable among MediaWiki developers and should be avoided for the time being.

Classes

Encapsulate your code in an object-oriented class, or add functionality to existing classes; do not add new global functions or variables. Try to be mindful of the distinction between ‘backend’ classes, which represent entities in the database (eg User, Block, Revision, etc), and ‘frontend’ classes, which represent pages or interfaces visible to the user (SpecialPage, Article, ChangesList, etc. Even if your code is not obviously object-oriented, you can put it in a static class (eg IP or Html).

As a holdover from PHP 4’s lack of private class members and methods, older code will be marked with comments such as /** @private */ to indicate the intention; respect this as if it were enforced by the interpreter.

Mark new code with proper visibility modifiers, including public if appropriate, but do not add visibility to existing code without first checking, testing and refactoring as required. It’s generally a good idea to avoid visibility changes unless you’re making changes to the function which would break old uses of it anyway.

Error handling

Don’t suppress errors with PHP’s @ operator, for any reason ever. It’s broken when E_STRICT is enabled and it causes an unlogged, unexplained error if there is a fatal, which is hard to support. Use wfSuppressWarnings() and wfRestoreWarnings() instead. The checkSyntax.php maintenance script can check for this error for you.

When your code encounters a sudden error, you should throw a MWException (or an appropriate subclass) rather than using PHP’s trigger_error. The exception handler will display this as nicely as possible to the end user and wiki administrator, and also provides a stack trace to developers.

'Coz sharing is caring

OOP & PHP5

Since the introduction of PHP 5 in 2004, PHP has had an object model worthy of that description and became a truly modern language for use on the web. Earlier PHP scripts would have been of the kind where, to quote from Alice’s Adventures, you would “Begin at the beginning, and go on till you come to the end: then stop.”

Nowadays that very procedural approach is less common in PHP, so this article takes a look at some of the basic object oriented features available in the language and shows some examples of using them with code examples.

Using OOP (Object Orientated Programming) enables us to architect our systems much more clearly, and to make them more manageable and more maintainable. This technique also allows us to separate form from function to create clean, navigable codebases with plenty of opportunities to reuse code, apply design patterns and bring in concepts from other brances of computer science.

Objects vs Classes
While the terms “object” and “class” are often used almost interchangeably in the world of software, there is a definite conceptual difference between the two. A class is the blueprint or recipe; it describes what the object should be, have and do. So a class might look like this:

class Elephpant {
    public $colour;

    public function dance() {
        echo &quot;elephpant dances!\n&quot;;
        return true;
    }
}

elephpant.php

An object, on the other hand, is an actual instantiation of the class – its an actual thing, with values and behaviours. In the example below, $ele is the object:

include('elephpant.php');

$ele = new Elephpant();

We can inspect $ele to make sure that it is, in fact, an object of the class Elephpant, using the print_r command. Adding this to our code sample as shown, we see the output below:

include('elephpant.php');

$ele = new Elephpant();
print_r($ele);

Elephpant Object
(
    [colour] =&gt;
)

This output shows an object, of type Elephpant, and with a single empty property named “colour”. For more information about the objects exact properties and their values, you can also use var_dump, which gives a more detailed output showing in detail the datatypes of each property. This is particularly useful for spotting empty strings, nulls and false.

Using Objects, Their Properties and Methods

Our class, Elephpant, has a property and a method (OO-speak for “function”) already defined inside it, so how can we interact with these? Let’s start by setting the colour property; we use the object operator which is a hyphen followed by a greater than sign.

include('elephpant.php');

$ele = new Elephpant();

// set the colour property
$ele-&gt;colour = &quot;blue&quot;;

// now use that property
echo &quot;The elephpant is &quot; . $ele-&gt;colour;

The output of this script reads “The elephpant is blue”. The property will remain set on the object until the object is destroyed, or the property overwritten or unset. Objects are a great way of keeping things together that belong together, for example information about an elephpant!

Similarly we can call the method using the same operator – the brackets after the call let PHP know its a method rather than a property, and if we had parameters to pass in they’d go between the brackets. Something like this:

include('elephpant.php');

$ele = new Elephpant();

// call the dance method
$ele-&gt;dance();

Look back at the class declaration for Elephpant and you’ll see the dance method actually echoes from within it. Indeed when we run the code example here, we see “elephpant dances!” as our output. It is a very trivial example but I hope it does show how to call methods against our objects. An alternative approach (and probably a better one within an actual application) would be to create the string and use it as the return value for the function. Then the calling code can take the string and echo it, or do whatever else it needs to, in a more flexible way.

Inheritance

Now we know how to create and interact with objects, let’s step things up a bit and look at how we can create objects which are similar in some ways and different in others, using inheritance. If you are accustomed to OOP from any other programming languages then this will seem very familiar to you, so here is a quick look at how this can be done in PHP. We already have our Elephpant class declared, so let’s add a Penguin class as well. They will both inherit from the parent class Animal, which looks like this:

class Animal{

    public $type = &quot;animal&quot;;

    public function dance() {
        echo $this-&gt;type . &quot; dances!\n&quot;;
        return true;
    }
}

animal.php

The animal has a “type” property, and a dance() method. It uses the type property in the dance() method to create the output, using $this to refer to the current object. In PHP, $this is a special keyword which refers to the current object from within its own class.
Now we can create a Penguin class that inherits from this general Animal class, by using the extends keyword to denote its parent:

class Penguin extends Animal {
    public $type = &quot;penguin&quot;;
}

penguin.php

The penguin class would inherit the type property set to “animal” if we didn’t override it by setting the property again in this class. However even without declaring a dance() method, the penguin can dance!

include('animal.php');
include('penguin.php');

$tux = new Penguin();

// make tux dance
$tux-&gt;dance();

The above example gives the output “penguin dances!” – using the dance() method from the Animal class, which is available because the Penguin class extends it, and the type property set separately in the Penguin class itself.

Access Modifiers

Take a look at the previous example. The type is set in the class, but we could easily set it from our main code if we wanted to. Imagine if we put $tux->type = “giraffe” before we asked him to dance! Sometimes this is the desired behavior, and sometimes it isn’t. To allow us to control whether properties can be changed outside a class, PHP gives us access modifiers. An example of these are the “public” keywords you see in the classes shown above. To prevent the type property being edited from outside the class, we can declare the Penguin type to be private, so the class now looks like this:

class Penguin extends Animal {
    private $type = &quot;penguin&quot;;
}

private_penguin.php

The following code listing shows us trying to set the now-private type property, and is followed by the resulting output.

include('animal.php');
include('private_penguin.php');

$tux = new Penguin();

// change the type
$tux-&gt;type = &quot;linux penguin&quot;;
// make tux dance
$tux-&gt;dance();

Fatal error: Access level to Penguin::$type must be public (as in class Animal) in /home/lorna/…/OOP/private_penguin.php on line 5

The resulting message feeds back to the user that the type property can’t be modified, and even includes the detail that the property was public in the parent class. Access modifiers are pretty powerful, we should look at them in more detail.

Access modifiers can be applied to properties and to methods and to properties. The options are public, private and protected. In PHP4, these weren’t available and everything is public. As a result, and to maintain backwards compatibility, if an access modifier isn’t specified then the property or method defaults to being public. This isn’t recommended practice however, and it is best to be explicit about which is intended.

Public: The public access modifier means that properties and methods can be accessed from anywhere, within the scope of the object itself, and also from outside code operating on an object.

Private: The method or property is only available from within the scope of this specific class. Before using this option, read on to find out about the “protected” access modifier.

Protected: The method or property is available from within this class, and from within any classes with extend or implement this class. This is ideal where you don’t want external code to change the class, but you do want to be able to extend the class later and take advantage of this property or method. Protected is more flexible than private and almost always the better choice.

Using these access modifiers we can control where our class methods and properties can be accessed from. We looked at an example of properties and this works in the same way for method calls – they cannot be accessed from outside of the class definition unless they are declared to be public. It can be very useful indeed to declare methods as protected, where they are internal helper methods used by other class methods but not intended to be accessed directly. In PHP4 there was no support for this and so the internal methods were sometimes named with an underscore to hint that this was their intended use – it is still possible to see this naming convention in use today, although it is not needed.

Using OOP in PHP: Practical Example

Object Oriented design is particularly useful where you have data objects that relate to one another – so it is very common for example to have OOP used to deal with data. PHP 5 has the PDO (PHP Data Object) classes which are a great way to talk to a backend database, either mysql or any other kind of database, and using the object oriented interface offered by this extension ties in well with the usage I have shown here.

A common mistake for those coming to OO for the first time is to declare methods inside a class but then instantiate a single copy of that and pass in data such as the ID of the data to each method. Here’s an example of a user class that does this:

class User {
    /**
     * getDisplayName
     *
     * @param int $user_id the user_id of the user in the database table
     * @access public
     * @return string Display name of this user
     */
    public function getDisplayName($user_id) {
        $sql = 'select display_name from users where user_id = '.$user_id;
        $results = mysql_query($sql);
        $row = mysql_fetch_array($results);
        return $row['display_name'];
    }

    /**
     * getFriends
     *
     * @param int $user_id the user_id of the user in the database table
     * @access public
     * @return array An array of friend_ids
     */
    public function getFriends($user_id) {
        $sql = 'select friend_id from user_friends where user_id = '.$user_id;
        $results = mysql_query($sql);
        $friends = array();
        while($row = mysql_fetch_array($results)) {
            $friends[] = $row['friend_id'];
        }
        return $friends;
    }
}

user.php

And some code that uses it:

include('user.php');
mysql_connect('localhost','root','');
mysql_select_db('test');

$user = new User();
echo &quot;User known as: &quot; . $user-&gt;getDisplayName(1) . &quot;\n&quot;;

$friends = $user-&gt;getFriends(1);
echo &quot;Friends with: &quot; . implode(', ',$friends) . &quot;\n&quot;;

If you want to run this code yourself, then you can set up the database tables using this script:

CREATE TABLE `user_friends` (
  `user_friend_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `friend_id` int(11) NOT NULL,
  PRIMARY KEY (`user_friend_id`)
)
INSERT INTO `user_friends` VALUES (1,1,3),(2,1,5);

CREATE TABLE `users` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(20) DEFAULT NULL,
  `last_name` varchar(50) DEFAULT NULL,
  `display_name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`user_id`)
)
INSERT INTO `users` VALUES (1,'Lorna','Mitchell','lornajane');

user.sql

This is more like a function library than an actual object, and although it works perfectly well and does have its applications, it can be better to aim to take advantage of more object oriented features. To do this, a new object should be created for each item the system handles, and if it has an ID and perhaps some other properties, these should be set as part of the object. Then rather than creating a single user object and doing getFriends(42) on it, you’d have a user with ID 42 which did $user->getFriends().

Here’s a follow up example with a class and how to use it, this will give better performance and enable you to clearly see which data goes with which object where there are multiple items on a page:

class User {
    /**
     * getUserById
     *
     * @param int $user_id the id of the user row in the table
     * @access public
     * @return true if the user was found
     */
    public function getUserById($user_id) {
        $sql = 'select first_name, last_name, display_name from users where user_id = ' . $user_id;
        $results = mysql_query($sql);
        $row = mysql_fetch_array($results);
        $this-&gt;user_id = $user_id;
        $this-&gt;first_name = $row['first_name'];
        $this-&gt;last_name = $row['last_name'];
        $this-&gt;display_name = $row['display_name'];

        // in real life, there would be escaping and error handling and we'd only return true if we got data
        return true;
    }

    /**
     * getDisplayName
     *
     * @access public
     * @return string Display name of this user
     */
    public function getDisplayName() {
        return $this-&gt;display_name;
    }

    /**
     * getFriends
     *
     * @access public
     * @return array An array of friend_ids
     */
    public function getFriends() {
        $sql = 'select friend_id from user_friends where user_id = '.$this-&gt;user_id;
        $results = mysql_query($sql);
        $friends = array();
        while($row = mysql_fetch_array($results)) {
            $friends[] = $row['friend_id'];
        }
        return $friends;
    }
}

user2.php

include('user2.php');
mysql_connect('localhost','root','');
mysql_select_db('test');

$user = new User();
// populate the object
$user-&gt;getUserById(1);
echo &quot;User known as: &quot; . $user-&gt;getDisplayName() . &quot;\n&quot;;

$friends = $user-&gt;getFriends();
echo &quot;Friends with: &quot; . implode(', ',$friends) . &quot;\n&quot;;

In Summary

This has been a very introductory look at some of the object oriented features available in PHP, to get you started out with the basics of working with OO code and also writing your own. If this has helped you take your first OOP steps, then let us know by leaving a comment and let us know what you built! In the next post there will be some more in-depth content including using constructors, access modifiers and working with the static keyword in PHP – taking your skills to the next level.

'Coz sharing is caring