Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 89

Chapter Two

PHP
Companies that Use PHP
Contents
Basics of PHP
Control structure
Function
Array
Classes
Objects
Members (Data & Function)
Inheritance, Encapsulation, Abstraction and
Polymorphism
Introduction to PHP

• PHP-Hypertext Preprocessor.
• Is a server-side scripting language.
– Capable of generating the HTML pages

• HTML generates the web page with static text and


images.
• However, the need evolved for dynamic web-based
applications, mostly involving database usage.
Cont…PHP

• PHP files can contain text, HTML, JavaScript code,


and PHP code
• PHP code are executed on the server, and the result is
returned to the browser as plain HTML
• PHP files have a default file extension of ". php"
Why PHP?
There are many features that make PHP more
affordable for than other web scripting languages :
 Performance: Script written in PHP executes much
faster than those scripts written in other languages
such as JSP & ASP.
 Open Source Software: PHP source code is free
available on the web. You can develop all the
versions of PHP according to your requirement
without paying any cost. All its components are free
to download and use.
Continued…
 Platform Independent: PHP are available for
WINDOWS, MAC, LINUX & UNIX operating
system. A PHP application
developed in one OS can be easily executed in other
OS also.
 Compatibility: PHP is compatible with almost all
local servers used today like Apache, IIS etc.
 Embedded: PHP code can be easily embedded
within HTML tags and script.
Continued…
Common uses of PHP
 PHP can generate dynamic page content
 PHP can create, open, read, write, and close files
on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your
database
 PHP used for form validation
 PHP can restrict users to access some pages on your
website 9

 PHP can encrypt data


Install PHP
 To install PHP, AMP (Apache, MySQL, PHP)
software stack is suggested. It is available for all
operating systems.
 WAMP for Windows
 LAMP for Linux
 MAMP for Mac
 SAMP for Solaris
 FAMP for FreeBSD
 XAMPP (Cross platform, Apache, MySQL,
PHP, Perl) for Cross Platform: It includes some
other components too such as FileZilla,
OpenSSL, Webalizer, Mercury Mail etc.
11
Basic PHP Syntax
 Syntax
 PHP code should enclosed within:
<?php and ?>
 Contents between <?php and ?> are executed as PHP code
• PHP code can be embedded in HTML
 All other contents are output as pure HTML
Example:
<p>This is going to be ignored.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored.</p> HTML content
<?php
PHP code
?>
HTML content ...
Including PHP in a Web Page
 There are 4 ways of including PHP in a web page
1. <?php echo("Hello world"); ?>
2. <script language = "php">
echo("Hello world");
</script>
3. <? echo("Hello world"); ?>
4. <% echo("Hello world"); %>
 You can also use print instead of echo
 Method (1) is clear and unambiguous
 Method (2) is useful in environments supporting mixed
scripting languages in the same HTML file (most do not)
 Methods (3) and (4) depend on the server configuration
Comments
# single-line comment
// another single-line comment style
/*
multi-line comment
*/
 like Java and JavaScript but # is also allowed
-a lot of PHP code uses # comments instead of //
Data Types
 Boolean (bool or boolean)
 Simplest of all
 Can be either TRUE or FALSE
 Integer (int or integer)
 Hold integer values (signed or unsigned)
 Floating point (float or double or real)
 Hold floating point values
 String (string)
 Hold strings of characters within either ‘ or ‘’
 Escaping of special characters can be done using \
 Ex. “this is a string”, ‘this is another string’,
“yet \”another\” one”
Cont’d
 Array
 Collection of values of the same data type
 Object
 Instance of a class
 Resource
 Hold a reference to an external resource created by some
functions
 NULL
 Represents that a variable has no value
 A variable is considered to be NULL if
• it has been assigned the constant NULL.
• it has not been set to any value yet.
• it has been unset()
Type Casting
The casts allowed are:
 (int), (integer) - cast to integer
 (bool), (boolean) - cast to boolean
 (float), (double), (real) - cast to float
 (string) - cast to string
 (array) - cast to array
 (object) - cast to object
Variable
 All variables in PHP start with a $ sign symbol.
 The correct way of setting a variable in PHP:
 $var_name = value;
 variable does not need to be declared before being
set.
 PHP automatically converts the variable to the
correct data type, depending on how they are set.
 A variable name must start with a letter or an
underscore "_"
 A variable name can only contain alpha-numeric
characters and underscores (a-Z, 0-9, and _ )
Variables (cont’d)
Example

<?php
$name= 'Bob';
$Name= 'Joe';
Echo "$name, $Name"; //outputs "Bob, Joe"
$4site = 'not yet'; // invalid; starts with a number
$_4site = 'not yet'; //valid; starts with an underscore
cont’d
1. Function isset tests if a variable is assigned or not
$A = 1;
if (isset($A))
print “A isset” if (!
isset($B))
print “B is NOT
set”;
2. Using $$
$help = “hiddenVar”;
$$help = “hidden
Value”;
echo $$help; // prints
hidden Value
20
$$help = 10;
cont’d
• Character escaping
– If the string is enclosed in double-quotes ("),
PHP understands more escape sequences for
special characters:
sequence meaning
\n linefeed
\r carriage return
\t horizontal tab
\\ backslash
\$ dollar sign
\" double-quote
21
Variable scope
PHP has four different scopes:
– Local: a variable declared within a PHP function
– global: a variable that is defined outside of any
function
• To access a global variable from within a function,
use the global keyword
– Static: when a function is completed, all of its
variables are normally deleted.
• However, sometimes you want a local variable to
not be deleted.
• To do this, use static keyword
– Parameter: is a local variable whose value is
passed
the function by the calling code
• E.g. Function($X)
22
Cont…
• Several predefined variables in PHP are
"superglobals", which means that they are always
accessible, regardless of scope - and you can access
them from any function, class or file without having
to do anything special.
• The PHP superglobal variables are:
$GLOBALS
$_SERVER
$_REQUEST
$_POST
$_GET
$_FILES
$_ENV
$_COOKIE
$_SESSION
23
Example
//local //Global // static
<?php <?php <?php
$x = 5; $x = 5; function myTest() {
$y = 10;
$y = 10; static $x = 0;
function myTest() { echo $x;
function myTest() {
$x=4, $y=6; $GLOBALS['y'] = $x++;
$y = $x + $y; $GLOBALS['x'] + }
echo $y; $GLOBALS['y']; myTest();
} } myTest();
myTest(); myTest();
myTest();
echo $y; // echo $y; // outputs 15 ?>
outputs
?> 10 ?> //outputs
012

24
PHP String Variables
• A string variable is used to store and manipulate text.
• String variables are used for values that contain
characters.
A string can be used directly in a function or it can be
stored in a variable.
• Below, the PHP script assigns the text "Hello World"
to a string variable called $txt:
<?php
$txt="Hello World";
echo $txt;
?>
The output of the code above will be: Hello World
25
Cont’d
 Variables within double quoted strings (“”) are parsed
Example
$name = “Abebe”;
$message = “Hello $name”;
echo $message; //Hello Abebe
 Variables within single quoted strings (‘’) are not
parsed!
Example
$name = “Abebe”;
$message = ‘Hello $name’;
echo $message; //Hello $name
Cont’d
 Variable parsing – variables within double quoted
strings are parsed.

Example
<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works
echo "He drank some $beers"; // won't work
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>
“ or ‘
Difference between strings written in single and
double quotes:
 In a double-quoted string any variable names are
expanded to their values.
 In a single-quoted string, no variable expansion takes
place. <?php
$name = ‘Phil’;
<?php $age = 23;
$name = ‘Phil’; echo ‘$name is $age’;
$age = 23; // $name is $age
echo “$name is $age”; ?>
// Phil is 23
?>
Concatenation
Use a period/ dot (.) to join strings into one

<?php
$string1=“Hello”;
$string2=“PHP”;
$string3=$string1 . “ ” . $string2;
print $string3;
?>
Hello PHP
Output
 There are two language constructs available to display data:
print() and echo()
 They can be used with or without brackets
 Note that the data ‘displayed’ by PHP is actually parsed by
your browser as HTML
<?php
echo ‘Hello World!<br>’;
echo(‘Hello World!<br>’);
print ‘Hello World!<br>’;
print(‘Hello World!<br>’);
?>
Echo example
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
echo $bar; // Outputs Hello
echo $foo,$bar; // Outputs 25Hello
echo “5x5=”,$foo; // Outputs 5x5=25
echo “5x5=$foo”; // Outputs 5x5=25
echo ‘5x5=$foo’; // Outputs 5x5=$foo
?>
 Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it
with 25
 Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP.
 This is true for both variables and character escape-sequences (such
as “\n” or “\\”)
PHP Forms
 Input to server side scripts comes from clients through
forms
 Two methods of sending data: GET & POST
 GET
• Search queries and small amounts of data
• Also generated when a user clicks on a link
• Non secure (displayed in address bar)
 POST
• Large and secure data
 The default method for HTML forms is GET
 To access form field values in PHP, use the built-in PHP
arrays: $_GET and $_POST respectively for GET and POST
request methods
Cont’d
 The names of the form fields will be used as indices in the
respective arrays
 For example, to access the value of an input box named
‘first_name’ in a form whose method is POST, write:
$_POST[ ‘first_name’ ]
 If the form method is GET,
$_GET[ ‘first_name’ ]
Example:
<form method=‘POST’ action=“login.php”>
<input type=‘text’ name=‘username’><br>
<input type=‘password’
name=‘password’><br>
<input type=‘submit’ value=‘login’>
</form>
Cont’d
//login.php
<?php
$username = $_POST[ ‘username’ ];
$password = $_POST[ ‘password’ ];
if($username == “user” && $password == “pass”){
//login successful
header( ‘Location: home.php’ );
exit();
}else{//login failed
header( ‘Location: login.html’ );
exit();
}
} ?>
PHP Form Handling
• The PHP superglobals $_GET and $_POST are used to
collect form-data.
• GET vs. POST
– Both GET and POST create an array (e.g. array( key =>
value, key2 => value2, key3 => value3, ...)). This array
holds key/value pairs, where keys are the names of the
form controls and values are the input data from the
user.
– Both GET and POST are treated as $_GET and $_POST.
Cont’d
These are superglobals, which means that they are
always
accessible, regardless of scope - and you can access
them from any function, class or file without having to
do anything special.
– $_GET is an array of variables passed to the current
script via the URL parameters.
– $_POST is an array of variables passed to the current
script via the HTTP POST method.
When to use GET?
• Information sent from a form with the GET method is
visible to everyone (all variable names and values are
displayed in the URL).
• GET also has limits on the amount of information to send.
• The limitation is about 2000 characters. However,
because the variables are displayed in the URL, it is
possible to bookmark the page. This can be useful in some
cases.
• GET may be used for sending non-sensitive data.
• Note: GET should NEVER be used for sending
passwords or other sensitive information!
When to use POST?
• Information sent from a form with the POST method
is invisible to others (all names/values are embedded
within the body of the HTTP request)
• Has no limits on the amount of information to send.
• POST supports advanced functionality such as
support for multi-part binary input while
uploading files to server.
• However, because the variables are not
displayed in the URL, it is not possible to
bookmark the page.
• Developers prefer POST for sending form data.
Example
<--! welcome.php -->
<html>
<--! <--! indexget.html-->
<body>
indexpost.html-- <html>
Welcome <?php echo
<body>
> <form
$_POST["name"]; ?><br>
Your email address is:
<html> action="welcome_get.php"
<?php echo
method="get">
<body> Name: <input type="text"
$_POST["email"]; ?>
<form name="name"><br> </body>
action="welcom E-mail: <input </html>
e.php" <--!welcome_get.php
type="text" <html>
method="post"> name="email"><br> <body>
Name: <input <input type="submit"> Welcome <?php echo
type="text" $_GET["name"]; ?><br>
</form>
name="name">< Your email address is:
br> <?php echo
</body>
$_GET["email"]; ?>
E-mail: <input </html> </body>
type="text" </html>
Post Output

indexpost.html Hide username and email

The page directed to welcome.php when the user clicks submit query button
Get Output
Shows username and email on URL
indexget.html

The page directed to welcome_get.php when the user clicks submit query
button
Cont’d
 In effect, all form data will be available to PHP scripts
through the appropriate array: $_GET or $_POST
 Another way of getting input from client can be using
cookies
 Cookie is information stored on the client by the server
 Cookies stored on a client associated to a particular
server are sent to the server every time that same client
computer requests for a page
 Cookies are often used to identify a user
Cont’d
 To create a cookies, use the setcookie() function
 Cookies must be sent before any output from your
script.
 This function must be called before any other output in
the PHP file, i.e before <html>, any spaces, …
 To retrieve a cookie value, use the $_COOKIE array
with the name of the cookie as index
<html><body>
<?php if( isset( $_COOKIE[ “uname” ] ) )
echo “Welcome “ . $_COOKIE[ “uname” ] . “! <br> “;
else
echo “Cookie not set <br>”;
?>
Operators
Arithmetic
 +, -, *, /, %, --, ++
Assignment (simple, compound)
 =, +=, -=, *=, /=, %=
Comparison
 ==, != , ===, !==, <, >, <=, >=
Logical
 &&, || , !
String
 . (dot)
Arithmetic Operators

Operator Name Example Result

+ Addition $x + $y Sum of $x and $y


- Subtraction $x - $y Difference of $x and $y
* Multiplication $x * $y Product of $x and $y
/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by $y

** Exponentiation $x ** $y Result of raising $x to the


$y'th power (Introduced in
PHP 5.6)
Arithmetic Operations
<?php
$a=15;
$b=30;
$total=$a+$b;
Print $total;
Print “<p><h1>$total</h1>”;
// total is 45
?>
$a - $b // subtraction
$a * $b // multiplication
$a / $b // division
$a += 5 // $a = $a+5 Also works for *= and /=
PHP Control Structures
 Control Structures: allow us to control the flow of execution
through a program or script.
 Grouped into conditional (branching) structures (e.g. if/else)
and repetition structures (e.g. while loops)
• In PHP we have the following conditional
statements:
• if statement - use this statement to execute some code only
if a specified condition is true
• if...else statement - use this statement to execute
some code if a condition is true and another code if
the condition is false
• if...else if....else statement - use this statement to select
one of several blocks of code to be executed
• switch statement - use this statement to select one of
many blocks of code to be executed
Cont…
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
?>
</body>
</html>
Cont…
<html> <body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body></html>
Cont…
<html><body>
<?php
$d=date("D");
if ($d=="Fri")
{
echo "Hello!<br />";
echo "Have a nice weekend!";
echo "See you on Monday!";
}?>
Cont…
<html><body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else if ($d=="Sun")
echo "Have a nice Sunday!";
else
echo "Have a nice day!"; ?> </body></html>
Cont…
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and
label2;
Cont…

<html><body>
<?php
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break; Next slide
Cont…
case 3:
echo "Number 3"; break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>
Cont’d

 Break
 ends execution of the current for, for-each, while, do-while, or
switch structure
 Continue
 used within looping structures to skip the rest of the current loop
iteration
 Return
 If called from within a function, the return statement immediately
ends execution of the current function, and returns its argument
as the value of the function call
Loops in PHP
 ‘For’ Loop
for(var=initial;condition;incr/decr)
{
statements;
}
 ‘While’ Loop
while (condition)
{
statements;
}
Cont’d
 ‘Do….While’ Loop

do{
statements;
}
while (condition);

 Foreach(for array expression)

foreach (array_expr as $value) { statement }


While loop flow chart
Example
1.<?php
2. $i = 'A';
3. while ($i < ‘F') {
4. echo $i;
5. $i++;
6. echo "</br>";
7. }
8.?>
Output: A B C D E
Do…While loop flow chart
Example
1.<?php
2. $x = 1;
3. do {
4. echo "1 is not greater than 10.";
5. echo "</br>";
6. $x++;
7. } while ($x > 10);
8. echo $x;
9.?> Output: 1 is not greater than 10.
PHP Arrays
• Array – a special variable, which can store
multiple values in one single variable
• There are 3 types of arrays in PHP
– Indexed(numeric) arrays
– Associative arrays
– Multidimensional arrays
Cont…
• Indexed(Numeric) Arrays
– A numeric array stores each array element with a
numeric index.
– There are two methods to create a numeric array.
1. In the following example the index are automatically
assigned (the index
starts at 0):
• $cars=array("Saab","Volvo","BMW","Toyota");
2. In the following example we assign the index manually:
• $cars[0]="Saab";
• $cars[1]="Volvo";
• $cars[2]="BMW";
• $cars[3]="Toyota";
Example
<?php
$cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
echo $cars[0] . " and " . $cars[1] . " are Swedish
cars.";
?>
The code above will output:
Saab and Volvo are Swedish cars.
Cont…
• Associative Arrays
– An associative array, each ID key is
associated with a value.
– When storing data about specific named values,
a numerical array is not always the best way to
do it.
– With associative arrays we can use the values
as keys and assign values to them.
Cont…
• In this example we use an array to assign ages
to the different persons:
– $ages = array("Peter"=>32, "Quagmire"=>30,
"Joe"=>34);

• This example is the same as above, but


shows a different way of creating the array:
– $ages['Peter'] = "32";
– $ages['Quagmire'] = "30";
– $ages['Joe'] = "34";
Cont…
• The ID keys can be used in a script:
<?php
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
echo "Peter is " . $ages['Peter'] . " years old.";
?>
The code above will output: Peter is 32 years old.
Cont…
• Multidimensional Arrays
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2), array("Land Rover",17,15)
);
• Accessing multidimensional array

echo $cars[0][2];// 18
echo $cars[1][1];// 15
Classes in PHP
A class is a template/ blueprint for objects.
A class is defined by using the class keyword,
followed by the name of the class and a pair of curly
braces ({}).
All its properties and methods go inside the braces.
<?php
class Fruit {
// code goes here...
}?>
Class Example
<?php
class Fruit {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}}
?>
What is an Object?
An object is a thing, anything, just as things in the
real world.
o E.g. (cars, dogs, money, books, … )
In the web browser, objects are the browser window
itself, forms, buttons, text boxes, …
Methods are things that objects can do.
◦ Cars can move, dogs can bark.
◦ Window object can alert the user “alert()”.
All objects have properties.
◦ Cars have wheels, dogs have fur.
◦ Browser has a name and version number.
Example of an Object
 <?php
class Fruit {
// Properties
public $name;
public $color;

// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$apple = new Fruit();
$banana = new Fruit();
$apple->set_name('Apple');
$banana->set_name('Banana');

echo $apple->get_name();
echo "<br>";
echo $banana->get_name();
?>
PHP Functions

 The real power of PHP comes from its functions.


 In PHP, there are more than 700 built-in functions.
 You can put your script into a function to keep the
browser from executing a script when the page
loads.
 The function will be executed by a call to the
function.
You may call a function from anywhere within a
page.
Cont…

Creating PHP Function

Syntax

function functionName()

//code to be executed;

}
Cont…
A simple function that writes my name when it is called:
<html><body>
<?php
function writeName()
{
echo "Jemal Hailu";
}
echo "My name is ";
writeName(); // function calling
?>
</body></html>

Output: My name is Jemal Hailu.


Cont…
Adding parameters
– To add more functionality to a function, we can add parameters. A parameter is
just like a variable.
– Parameters are specified after the function name, inside the parentheses.
<html>
<body>
<?php
function writeName($fname)

{
echo $fname . " Refsnes.<br />";
}
echo "My name is "; writeName("Kai
Jim"); Output:
echo "My sister's name is ";
writeName("Hege"); My name is Kai Jim Refsnes.
echo "My brother's name is "; My sister's name is Hege Refsnes.
writeName("Stale"); My brother's name is Stale Refsnes.
?>
</body>
Cont…
Return values
To let a function return a value, use the return statement.
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
Output: 1 + 16 = 17
Cont…
Passing by value

function salestax($price,$tax){

$total=$price + ($price*$tax);
echo” Total cost:$total”;
}
salestax($42,$0);

This returns the following:


Total cost:$42.00
Passing by reference
– changes made to an argument within a function to be reflected
outside of the function’s scope
– done by appending an ampersand to the front of the argument

<?php
$cost = 20.00;
$tax = 0.05;
function calculate_cost(&$cost, $tax)
{
// Modify the $cost variable Output:
$cost = $cost + ($cost * $tax); Tax is 5%
// Perform some random change to the $tax var Cost is $21
$tax += 4;
}
calculate_cost($cost,$tax);
echo "Tax is: ". $tax*100; echo "Cost is: $". $cost;
?>
Predefined functions
 Arithmetic functions
floor, ceil, round, abs, min, max, rand, etc.
 String functions
strlen, strcmp, strpos, substr, strtolower, strtoupper
chop – remove whitespace from the right end
trim – remove whitespace from both ends
ltrim – remove whitespace from the left end
strlen() function
 The strlen() function is used to return the length of
a string.
 Let's find the length of a string:
<?php
echo strlen("Hello world!");
?>
 The output of the code above will be: 12
4 Pillars for OOP
1. Abstraction
 Abstraction is the process of showing only
essential/necessary features of an entity/object to the
outside world and hide the other irrelevant information.
 For example to open your TV we only have a power
button, It is not required to understand how infra-red waves
are getting generated in TV remote control.
Cont…
2. Encapsulation
 Encapsulation means wrapping up data and member
function together into a single unit i.e. class.
 Encapsulation is a protection mechanism for the data
members and methods present inside the class.
 Encapsulation automatically achieves the concept of data
hiding providing security to data by making the variable
private and exposing the property to access the private data
which would be public.
Cont…
3. Inheritance
 The ability of a class to derive or inherit the properties and
characteristics from another class is called inheritance.
 Inheritance is when an object acquires the property of
another object.
 Inheritance allows a class (subclass) to acquire the
properties and behavior of another class (super-class).
 It helps to reuse, customize and enhance the existing code.
Cont…
 So it helps to write a code accurately and reduce the
development time.
 Using the term extends, we inherit the characteristic of a
parent class.
 Syntax:
Class ChildClass extends ParentClass
 In the above syntax, ChildClass is a derived class (also
called extended class and subclass) that extends
ParentClass (also called superclass and base class).
Cont…
4. Polymorphism
 polymorphism means "many forms".
 A subclass can define its own unique behavior and still
share the same functionalities or behavior of its
parent/base class.
 A subclass can have their own behavior and share some of
its behavior from its parent class not the other way around.
 A parent class cannot have the behavior of its subclass.
Cont…
 Polymorphism is essentially an OOP pattern that enables
numerous classes with different functionalities to execute
or share a common Interface.
 The usefulness of polymorphism is code written in
different classes doesn't have any effect which class it
belongs because they are used in the same way.
<?php // Polymorphism Example
interface Machine {
public function calcTask(); }
class Circle implements Machine {
private $radius; public function __construct($radius)
{
$this -> radius = $radius;
}
public function calcTask(){
return $this -> radius * $this -> radius * pi(); } }
class Rectangle implements Machine {
private $width; private $height;
public function __construct($width, $height){
$this -> width = $width; $this -> height = $height;
}
public function calcTask(){
return $this -> width * $this -> height;} }
$mycirc = new Circle(3);
$myrect = new Rectangle(3,4);
echo $mycirc->calcTask(); Output : 28.274
echo $myrect->calcTask(); 12
?>
Any Question?

You might also like