Php

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

c++ destructor

"In C++ and C#, the destructor's name for the class ClassName is ~ClassName, the corollary of the constructor, which is ClassName. Java does not support destructors." Excerpt From: Ullman, Larry. "PHP Advanced and Object-Oriented Programming: Visual Quickpro Guide, Third Edition." iBooks.

Inheritance constructor example

"The Square class is derived from Rectangle but has its own constructor. That constructor, not Rectangle's, will be called when an object of type Square is created.

class names and function names are not case sensitive

"function names in PHP are not case-sensitive, the same is true for method names in classes."

initialize class attribute

"if an attribute is initialized with a set value, that value must be a literal value and not the result of an expression: Click here to view code image class GoodClass { public $var1 = 123; public $var2 = 'string'; public $var3 = array(1, 2, 3); } class BadClass { // These won't work! public $today = get_date(); public $square = $num * $num;"

call the methods of the class, you use this syntax

$object->methodName(); $object->methodName(arg1, arg2, arg3,...)

To access an object's properties

$object->propertyName;$object-$propertyName; // Error!

$this

$this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object)

$this is not available inside static function

$this, which always refers to the current object, is not available inside a static method, because static methods are meant to be invoked without using an object.

Creating an instance Example

<?php $instance = new SimpleClass(); // This can also be done with a variable: $className = 'SimpleClass'; $instance = new $className(); // new SimpleClass() ?>

php class example

<?php class SimpleClass { // property declaration public $var = 'a default value'; // method declaration public function displayVar() { echo $this->var; } } ?>

access a member of a newly created object in a single expression

<?php echo (new DateTime())->format('Y'); ?>

interface benefits

Another benefit that interfaces have over using abstract classes and inheritance is that classes in PHP cannot inherit from multiple parents. Classes, however, can implement multiple interfaces by separating each by a comma: Click here to view code image class SomeClass implements iA, iB {

private variable convention

As a convention, private variable names are often begun with an underscore. This is commonly done in many OOP languages, although it is not required.

Php Class Definition Format

Basic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly braces which enclose the definitions of the properties and methods belonging to the class.

class constants

Class Constants Class constants are like static attributes in that they are accessible to all instances of that class (or derived classes). But as with any other constant, the value can never change.

const keyword

Class constants are created using the const keyword, followed by the name of the constant (without a dollar sign), followed by the assignment operator and the constant's value: class SomeClass { const PI = 3.14; }

composition

Composition represents a "has a" relationship, where one class's property values are objects of another class type. For example, Employee is not a subtype of Department (i.e., a child), but rather a part of a Department's composition.

how to access static or constant attributes

Constants, like static attributes, also cannot be accessed through the object. You cannot do this: $obj->PI or $obj::PI But you can use ClassName::CONSTANT_NAME (e.g., SomeClass::PI) anywhere. You can also use self::CONSTANT_NAME within the class's methods.

final method and class

Final Methods Most methods in classes can be overridden. The exception is if a function is defined as final: final function myFunc() {...} A final method's definition cannot be altered by any subclass. A class can also be declared final, meaning that it cannot be extended.

how to reference a namespace

First include the file that defines the namespace, then use backslashes to indicate a namespace is being used. E.G. require('SomeNameSpace.php'); $obj = new \SomeNameSpace\SomeClass(); Or: require('MyUtilities\User\User.php'); $obj = new \MyUtilities\User\Login();

autoload part4

For each new object type created in the following code, the function will be invoked: $obj = new Class(); $me = new Human(); $r = new Rectangle(); Thanks to the _ _autoload() function, those three lines will automatically include Class.php, Human.php and Rectangle.php

copying and cloning part 3

If you actually want two separate, individual objects, you need to create a clone: $a = new SomeClass(); $a->val = 1; $b = clone $a; // Separate objects! $b->val = 2; echo $a->val; // 1 When the clone operator is used, PHP will perform what's called a "shallow copy." If you want to change how a clone of an object is made, you can define a _ _clone() method within the class. That method would be called whenever a clone is made, and would handle the cloning as you see fit. See the PHP manual for details.

Copying and Cloning Objects Part 1

In PHP 5, when you create a copy of an object, PHP actually creates a new reference to that object, not an entirely new object. In other words, both variables will point to the same thing, and changes made through one object will be reflected by the other: $a = new SomeClass(); $a->val = 1; $b = $a; $b->val = 2; echo $a->val; // 2

composition UML

In UML, composition is indicated by drawing a line with a diamond at one end from the included class (e.g., Employee) to the composite class (e.g., Department).

interface part 1

Interfaces, like abstract classes, identify the functionality (i.e., the methods) that must be defined by a specific class. To create an interface, use the interface keyword. Then, within the curly brackets, define the method signatures, not their actual implementation: interface iSomething { public function someFunction($var); }

copying and cloning part 2

More formally put, this means that PHP assigns objects by reference, not by value. PHP does this for performance reasons, as having multiple copies of entire objects, when not needed, is expensive.

subnamespace

Namespaces can have subnamespaces. To do that, indicate a subnamespace using the backslash: namespace MyUtilities\UserManagement; class Login {}

interface part 2

Note that all methods in an interface must be public. Also, interfaces only identify methods; they never include attributes. To associate a class with an interface, use the implements operator in the class definition: class Someclass implements iSomething {}. Fatal error will becreated by having a class implement an interface without implementing all of the interface's methods.

overloading

Overriding a method in such a way that it also takes a different number of arguments than the original is referred to as overloading a method. This can be accomplished in PHP but not as easily as overriding one.

constructor inheritance

PHP will always call the constructor for the class just instantiated . The same rule applies for destructors. Further, unlike in some other OOP languages, in PHP, when you create an object of a child class, the parent class's constructor is not automatically called.

_ _toString

The _ _toString() Method If you define a _ _toString() method in a class, PHP will invoke that method automatically when an object of that type is used as a string. For example, it would be called if you attempted to do this: $a = new SomeClass(); echo $a;

function's signature

The combination of a function's name and its arguments (the number of arguments, specifically) is referred to as the function's signature. In PHP 5, except for constructors, any derived class must use the same signature when overriding a method.

Abstract Class vs. Interface

The difference between an interface and an abstract class may seem subtle. Remember that an abstract class is meant to be extended by a more specific class, of which you'll probably create an object instance. As you've already seen, an abstract class might define a generic object, such as a shape. Conversely, an interface is not inherited by a class, so you should not think of an interface as a way of loosely defining an entire object. Instead, an interface establishes a contract for the functionality that a class must have, regardless of the class type. For example, in Chapter 8, "Using Existing Classes," you'll learn about the Iterator interface defined within the Standard PHP Library (SPL). The Iterator interface dictates the methods that must exist in a class in order for PHP to be ...

how to create a trait

To create a trait, use the trait keyword, followed by the name and definition: trait tSomeTrait { // Attributes function someFunction() { // Do whatever. } }

new

To create an instance of a class, the new keyword must be used.

define a namespace

To define a namespace, you'll want to create a new file that will only store the namespaced code. Create a namespace by using the namespace key-word, followed by the identifier: namespace SomeNamespace;

override a method

To override a method in PHP, the subclass must define a method with the exact same name and number of arguments as the parent class.

parent keyword

To refer to a member of a parent class, use the scope resolution operator with the keyword parent: class SomeOtherClass extends SomeClass{ function _ _construct() { parent::doThis(); } }

traits can have abstract methods

Traits can have abstract methods that must then be implemented by any class that uses the trait.

Type Hinting

Type hinting is the programming act of indicating what type of value is expected. For example, what type of value a function expects to receive for a parameter. Type hinting doesn't play much of a role in procedural PHP code because you cannot hint simple types (e.g., integers or strings). But you can hint object types, which is more useful.

Unified Modeling Language

Unified Modeling Language (UML), a way to graphically represent your OOP designs.

autoload part1

When you define a class in one script that is referenced in another script, you have to make sure that the second script includes the first, or there will be errors. To that end, PHP 5 supports a special function called _ _autoload

keyword self

Whereas you can use $this within a class to refer to the current object instance, the keyword self is a reference to the current class:

autoload part5

_ _autoload() function is defined outside of any class; instead, it is placed in a script that instantiates the objects.

autoload part2

_ _autoload() function is invoked when code attempts to instantiate an object of a class that hasn't yet been defined.

autoload part3

__autoload() function goal is to include the corresponding file. In simplest form, this might be function _ _autoload ($class) { require($class . '.php'); }

static function variable

a static function variable remembers its value each time a function is called image: function test() { static $n = 1; echo "$n<br>"; $n++; }

purpose of namespace

as you begin utilizing more and more classes, including those defined by other developers and in third-party libraries, conflicts can occur if multiple classes have the same name. Namespaces prevent these conflicts by letting you organize your code into groups. This has the effect of allowing you to safely use descriptive names without concern for conflicts.

`new self` and `new static` example

class A { public static function get_self() { return new self(); } public static function get_static() { return new static(); } } class B extends A {} echo get_class(B::get_self()); // A echo get_class(B::get_static()); // B echo get_class(A::get_self()); // A echo get_class(A::get_static()); // A

class inheritance syntax

class ChildClass extends ClassName { }

destructor

class ClassName { // Attributes and methods. function _ _destruct() { // Function code. } } Destructors do differ from constructors and other methods in that they cannot take any arguments.

add methods to classes:

class ClassName { function functionName() { // Function code. } }

composition and type hinting example

class Department { private $_name; private $_employees; function _ _construct($name) { $this->_name = $name; $this->_employees = array(); } function addEmployee(Employee $e){ $this->_employees[] = e; echo "<p>" . {$e->getName()} . "has been added to " . {$this->_name} . "</p>"; } } class Employee{ private _name; function __construct($name) { $this->_name = $name;} function getName(){ return ($this->_name);} } $hr = new Department('Human Resources'); $e1 = new Employee('Jane Doe'); $e2 = new Employee('John Doe'); $hr->addEmployee($e1); $hr->addEmployee($e2); unset($hr, $e2, $e1);

trait example continued

class Rectangle { use tDebug; public width = 0; public length = 0; function __construct($w,$l) { this->$width = $w; this->$length = $l; } public function getArea(){ return (this->$width*this->length); } ...... }

implementing multiple interfaces

class SomeClass implements iA, iB { /* code */ }

self example

class SomeClass { function _ _construct() { self::doThis(); } protected function doThis() { echo 'done!'; } } self::doThis() will invoke the doThis() method of the current class

How to use Type Hinting

class SomeClass { function doThis(OtherClass $var) { } } If the argument passed to the doThis() method is not of type OtherClass, or of a derived subclass, PHP will generate a fatal error

static variable and static function example

class SomeClass { public static $counter = 0; function _ _construct() { self::$counter++ } } class SomeClass { public static function doThis() { // Code. } } echo SomeClass::$counter; // 0 SomeClass::doThis();

Square Class Definition

class Square extends Rectangle { function _ _construct($side = 0) { $this->width = $side; $this->height = $side; } } // End of Square class.

Triangle Class Example

class Triangle extends Shape { private $_sides = array(); private $_perimeter = NULL; function _ _construct($s0 = 0, $s1 = 0, $s2 = 0) { $this->_sides[] = $s0; $this->_sides[] = $s1; $this->_sides[] = $s2; $this->_perimeter = array_sum($this->_sides); } // End of constructor. public function getArea() { //code } } public function getPerimeter() { return $this->_perimeter; } }

analogy of namespace

compare namespaces to creating a directory structure on your computer. You cannot place two files named functions.php within the same folder. However, you can place one in the MyUtilities folder and another in the YourUtilities folder, thereby making both versions of functions.php available.

abstract keyword

defining an abstract class abstract class ClassName { } abstract function methodName(); abstract function methodName ($var1, $var2); abstract class Pet { protected $_name; abstract public function getName(); }

dynamically calling a class attribute

function printVar($var) { echo "<p>In Test, \$$var: '{$this->$var}'.</p>"; } } // End of Test class.

get_object_vars && get_class_methods

get_object_vars($this); $methods = get_class_methods($this);

instanceof

if ($obj instanceof SomeClass) { ...} Notice that you don't put the class's name in quotation marks. Also—and this is important—in order for this to work, the PHP script must have access to the SomeClass definition.

default destructing

if you don't forcibly delete the object , it will be deleted when the script stops running.

implement abstract method rule

implementation of the abstract method in the extended class—e.g., Cat::getName()—must abide by the same visibility or weaker. If the abstract function is public, the extended version must also be public. If the abstract function is protected, then the extended version can only be protected or public. You would never make an abstract method private, since a private method

trait

in PHP each class can only inherit from a single parent class, and there is no common parent class that each of them would have. The solution, then, is traits. Traits allow you to add functionality to a class without using inheritance. Like an abstract class and an interface, traits cannot be instantiated

a CRUD interface

interface iCrud { public function create($data); public function read(); public function update($data); public function delete(); } class User implements iCrud { private $_userId = NULL; private $_username = NULL; function _ _construct($data) { $this->_userId = uniqid(); $this->_username = $data['username']; } . function create($data) { self::_ _construct($data); } function read() { return array('userId' => $this->_userId, 'username' => $this->_username); } function update($data) { $this->_username = $data['username']; } public function delete() { $this->_username = NULL; $this->_userId = NULL; } }

:: operator

is used to access members through classes, not objects: ClassName::methodName(); ClassName::propertyName;

how to structure namespace

organize the files themselves using the same structure image. This isn't required.

polymorphism

override a parent class's method to customize it for the new class.

polymorphism 2

overriding methods creates polymorphism, where calling the same method can have different results, depending on the object type.

nested constructor

parent::_ _construct() and parent::_ _destruct()

three levels of visibility

public, protected, and private

include a class definition

require('HelloWorld.php');

include and require difference

require() (as opposed to include()), the script will stop executing with a fatal error if the file could not be included (and there is no point in continuing without this file).

`new self` and `new static`

self refers to the same class in which the new keyword is actually written. static, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.

incorporate multiple traits into a class

separate each trait by a comma: use tTrait1, tTrait2;

static variable

static variable is remembered across all instances of that class (across all objects based on the class). To declare a static attribute, use the static keyword after the visibility indicator: class SomeClass { public static $var = 'value'; }

instanceof and interface

the instanceof operator can also be used to test if a class implements an interface.

namespace should be the first line of code

this should be the first line of PHP code in a file, and that the file cannot even have any HTML before that PHP code. Any code that follows that line will automatically be placed within that namespace: namespace SomeNamespace; class SomeClass {}

a trait example

trait tDebug { public function dumpObject() { $class = get_class($this); $attributes = get_object_vars($this); $methods = get_class_methods($this); foreach ($attributes as $k => $v) { echo "<li>$k: $v</li>"; } foreach ($methods as $v) { echo "<li>$v</li>"; } echo '</li></ul>'; } // End of dumpObject() method. }

True and False symbol in PhP

true and false

delete an object

unset($object);

add a trait to a class

you add a trait to a class via the use keyword inside the class definition: class SomeClass { use tSomeTrait; // Rest of class. }

indicating visibility in UML

• +, for public • -, for private • #, for protected +name:string +_ _construct($pet_name:string):void

class attribute summary

• Are variables • Must be declared as public, private, or protected (I'll use only public in this chapter) • If initialized, must be given a static value (not the result of an expression)

what can be placed in a namespace

• Classes • Interfaces • Functions • Constants You couldn't create a namespace just to hold some variables.

A class at its core has three components:

• Its name • Its attributes • Its methods

constructor summary

• Its name is always _ _construct(). • It is automatically and immediately called whenever an object of that class is created. • It cannot have a return statement. The syntax for defining a constructor: class ClassName { public $var; function _ _construct(arg1=default1, arg2=default2,...) { // Function code. } }

where to use ::

• Within classes, to avoid confusion when inherited classes have the same attributes and methods • Outside of classes, to access members without first creating objects


संबंधित स्टडी सेट्स

ch. 3 health, wellness, and health disparities

View Set

Final review for bio 94 quiz 1-4

View Set

SAT/ACT Math Problem Recognition Hansen

View Set

Random selection and random assignment (ch 5)

View Set

OBGYN and Neonatal Resuscitation

View Set

Vocabulary and Analytical Reasoning IV

View Set

United States & Canada History/Geography

View Set

CSCS Testing and Evaluation/Organization & Administration/Nutrition

View Set