October 16 - ndgriffeth/Class-Notes-and-Lectures GitHub Wiki
Declaration:
class A
{
(class A members)
}
Data members and referring to data members:
class A
{
private $data1='data1'; // you can use initializers with data members
public $data2='data2';
}
$a = new A(); // create a new instance
print $a->data2; // access a public data member
Exercise: Try the above code, then add an access to the private data member. What do you expect to happen? What does happen?
Use __get to access private variables:
public function __get($name)
{
return $this->$name;
}
Things to notice:
- The function can always be defined in exactly this way. However, you may want "virtual" attributes whose values aren't stored, but are computed from other attributes -- the getter would be defined differently for those attributes. Or, attributes may be stored in a database -- their getter's would also have to be different.
- Class attributes (data members) are referred to as $this->name inside the class.
- $name is not an attribute (data member) of the class!!!
Exercise: Create a class with a public data member, a private data member, and a getter. Put an echo in the getter to see when it is called. From outside the class, access each of the two data members. When do you think the getter will be called? Are you right?
Use __set to allow setting a variable from outside the class:
public function __set($name, $value)
{
$this->$name = $value;
}
To get the setter to set the variable named "data1" to "newvalue", write __set('data1','newvalue')
Exercise: Repeat the previous exercise, using a setter.
Constructors initialize objects. The constructor for a class in PHP is __construct().
class A
{
function __construct($p1, $p2, $p3="abc")
{
$this->var1 = $p1;
$this->var2 = $p2;
$this->var3 = $p3;
}
... rest of class definition ...
}
$a1 = new A("x", "y");
$a2 = new A("alpha", "beta", "gamma");
Things to notice:
- Parameters are defined for constructors just like for other functions.
- The parameters are included inside parentheses after the class name in the "new" statement.
- Optional parameters are permitted for constructors, just like for any other function.
- Data member (attribute) initialization can be much more complicated than above.
When an object reference is used in a context where a string is expected (e.g., in a print or echo statement), the method __toString() is called. An obvious thing to do in a __toString() method is to provide values for all the data members, in a reasonable format.
class A
{
function __construct($p1, $p2, $p3="abc")
{
$this->var1 = $p1;
$this->var2 = $p2;
$this->var3 = $p3;
}
function __toString()
{
return "var1=$this->var1, var2=$this->var2, var3=$this->var3";
}
... rest of class definition ...
}
Exercise: Define a class with a constructor, a setter, a getter, and a toString method. Use the toString method to illustrate the effects of using/not using optional parameters in the constructor and of using the setters.
Unreferenced objects can create "memory leaks" -- that is, they occupy memory without doing anything useful in the program. Garbage collection usually gets rid of them. You can do some final processing on them, if you need to, using a destructor (__destruct).
One class can "contain" the attributes and methods of another class by "inheritance." You usually want to do this when they have an "is-a" relationship, as in "A bicycle is a vehicle" or "A car is a vehicle."
class bicycle extends vehicle
{
private $gender;
}
Exercises:
In Java and C++, a subclass constructor either calls a superclass constructor explicitly (to set the superclass variables) or the no-args superclass constructor is added to the subclass constructor by the compiler.
- What happens if you try to define multiple constructors in PHP?
- Is a superclass constructor automatically invoked in PHP if none is mentioned in the subclass constructor?
You can invoke the parent constructor with parent::__construct()
Various similarities and differences between PHP and Java/C++.
**PHP** | **Java/C++** |
constructor name is \_\_construct | constructor name is class name |
every variable must have an access modifier; the keyword "function" identifies functions, don't need access modifier (public is default) | separate sections for public, private, protected |
$var is referred to as $this->var inside the class | "this" is implied when referring to members inside the class |
public data member $var is referred to as $obj->var outside of the class | public data member var is obj->var outside the class |
the function \_\_get($name) is called when private attribute $name is accessed from outside the class; it returns the value. | each private data member must have its own getter, to be called when private attribute $name is accessed |
the function \_\_set($name), if it exists, is called when attempting to set the value of a private variable. | Each private variable must have its own setter |
specify a default value to indicate an argument is optional; optional arguments appear at end of argument list | varargs (use Object... ) to indicate a variable number of arguments; must be last argument |
__toString() is used (if defined) when an object is used in a context requiring a string | toString() works the same way in Java; the operator "<<" can be overloaded for this purpose in C++ |
Inheritance indicated by "class A extends B" | Same |
-
Write a php class to represent user name, address, nickname, and password information, along with an array of user purchases. Each entry in the array needs to include only the date and the dollar amount. Operations should include the magic constructor, setter, and getter, an operation to add a new entry to the array, and an operation to return all the entries matching a given date.
-
What happens if a subclass and a superclass specify all data memebers as private; they both have magic getters; and you try to get the value of a superclass data member of a subclass object?