[ Team LiB ] Previous Section Next Section

Workshop

Quiz

1:

How would you declare a class called emptyClass() that has no methods or properties?

2:

Given a class called emptyClass(), how would you create an object that is an instance of it?

3:

How can you declare a property within a class?

4:

How would you choose a name for a constructor method?

5:

How would you prevent a method from being accessed except from within the current class and child classes?

6:

How would you create a private method in PHP 4?

7:

How can you access and set properties or methods from within a class?

8:

How would you access an object's properties and methods from outside the object's class?

9:

What should you add to a class definition if you want to make it inherit functionality from another class?


Answers

A1:

You can declare a class with the class keyword:

class emptyClass {
}

A2:

You should use the new operator to instantiate an object:

$obj = new emptyClass( );

A3:

In PHP 4, you can declare a property using the var keyword:

class Point {
  // properties
  var $x = 0;
  var $y = 0;
}

Using PHP 5, you can also use the private, protected, or public keywords.

A4:

A constructor must either take the name of the class that contains it (for PHP 4 compatibility) or it should be named ___construct().

A5:

You can limit the availability of a method to the current class and child classes by using the protected keyword:

protected function dontTouchMe( ) {
  // no access outside current class and children
}

A6:

There is no way of enforcing privacy in PHP 4. There is, however, a convention that functions beginning with an underscore character should be treated as private:

function _pleaseDontTouchMe () {
// not enforceable
}

A7:

Within a class, you can access a property or method by combining the $this variable and the -> operator:

class Point {
  // properties
  public $x = 0;
  public $y = 0;

  // constructor
  function ___construct( $x, $y ) {
    // calling a method
    $this->moveTo( $x, $y );
  }

  // method
  public function moveTo( $x, $y ) {
    // setting properties
    $this->x = $x;
    $this->y = $y;
  }
}

A8:

You can call an object's methods and access its properties using a reference to the object (usually stored in a variable) in conjunction with the -> operator:

// instantiating an object
$p = new Point( 40, 60 );

// calling an object's method
$p->moveTo( 20, 200 );

// accessing an object's property
print $p->x;

A9:

For a class to inherit from another, it must be declared with the extends keyword and the name of the class from which you want to inherit:

class funkyPoint extends Point {
}


    [ Team LiB ] Previous Section Next Section