PHP/Class/Objects
Версия от 10:37, 26 мая 2010; (обсуждение)
Содержание
Comparing Objects with == and ===
<?php
class Employee { }
$Bob = new Employee( );
$Joe = clone $Bob;
print (int)($Bob == $Joe) . "\n";
print (int)($Joe === $Joe) . "\n";
class Employee {
public function __construct( ) {
$this->myself = $this;
}
}
$Bob = new Employee( );
$Joe = clone $Bob;
print (int)($Bob == $Joe) . "\n";
print (int)($Bob === $Joe) . "\n";
?>
Create a new class and create an instance then use its property and method
<?php
class Dog
{
var $name;
function bark()
{
print "Woof!";
}
}
$pooch = new Dog;
$pooch -> name = "new name";
print $pooch -> name . " says ";
$pooch -> bark();
?>
Creating a new object and assigning it to a variable
<?php
Class Cat {
// Constructor
function __constructor( ) {
}
// The cat meows
function meow( ) {
echo "Meow...";
}
// The cat eats
function eat( ) {
echo "*eats*";
}
// The cat purrs
function purr( ) {
echo "*Purr...*";
}
}
$myCat=new Cat;
?>
Object Initialization
<?php
class foo {
function do_foo() {
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();
?>
Object Overloading
<?php
class Data {
private $data = array();
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
if (isset($this->data[$name])) { return $this->data[$name]; }
}
public function __isset($name) {
return isset($this->data[$name]);
}
public function __unset($name) {
unset($this->data[$name]);
}
}
$data = new Data();
$data->name = "F";
echo "<p>The data value of "name" is {$data->name}</p>";
unset($data->name);
echo "<p>The value is ", isset($data->name) ? "" : "not ", "set.</p>";
?>
Object Properties
<?
class Item {
var $name = "item";
}
$obj1 = new Item();
$obj2 = new Item();
$obj1->name = "widget 5442";
print "$obj1->name<br />";
print "$obj2->name<br />";
?>
Objects Within Objects
<?
class DogTag {
public $Words;
}
class Dog {
public $Name;
public $DogTag;
public function bark( ) {
print "Woof!\n";
}
}
$poppy = new Poodle;
$poppy->Name = "Poppy";
$poppy->DogTag = new DogTag;
$poppy->DogTag->Words = "call 555-1234";
?>
Object Type Information
<?
class Dog {
public $Name;
private function getName( ) {
return $this->Name;
}
}
class Poodle extends Dog {
public function bark( ) {
print ""Woof", says " . $this->getName( );
}
}
$poppy = new Poodle;
$poppy->Name = "Poppy";
$poppy->bark( );
if ($poppy instanceof poodle) { }
if ($poppy instanceof dog) { }
?>