PHP Basics [Outline]

Posted by stevehaysom on Tue, 25 Jan 2022 07:26:33 +0100

brief introduction

  • PHP is a universal open source scripting language, server-side scripting language
  • PHP (Hypertext Preprocessor) Hypertext Preprocessor
  • PHP script execution on server

What is a PHP file

  • PHP can contain text, HTML, JavaScript, and PHP code
  • PHP code is executed on the server and the results are returned to the browser as pure HTML
  • The default file extension for php files is:. php

What PHP can do

  • Generating dynamic page content
  • Create, open, read, write, close files on the server
  • Collect form data
  • Send and receive cookie s
  • Add, delete, modify data in the database
  • Restrict user access to individual pages on the site
  • Encrypt data
  • With PHP, instead of just exporting HTML, you can output images, PDF files, and even flash movies
  • Output any file, such as XHTML, XML

Why choose PHP

  • Can run on different platforms (Windows, Linux, Mac OS, etc.)
  • Compatible with almost all servers currently in use (Apache, IIS, etc.)
  • Provide extensive database support
  • Free Admission
  • Easy to learn and run efficiently on the server side

Basic Grammar

  • PHP scripts can be placed anywhere in the document
  • PHP script to <? PHP start, end?>;
  • Each line of code in PHP must end with a semicolon
  • A semicolon is a delimiter used to separate instruction sets
  • Two basic instructions for outputting text in a browser: echo and print
<?php
    print "hello PHP";
    echo "hello world";
?>

Notes

  • Single line comment: //
  • Multiline comment: /* Comment content*/

variable

  • Variables are "containers" for storing information
  • Variables start with a $sign followed by the name of the variable
  • Variable names must consist of letters, numbers, and underscores. Numbers do not begin
  • Variable names are case sensitive

Note: PHP statements and PHP variables are case sensitive

Create variable

  • PHP is a weakly typed language
  • When creating a variable, you do not have to declare the data type of the variable to PHP
  • PHP automatically converts a variable to the correct data type based on its value
<?php
    $txt = "Hello PHP!";
    $x = 10;
    $y = 5.5;
    $r = $x + $y;
    echo $txt,$r;
?>

Run Screenshot

Variable Scope

  • The scope of a variable is the part of the script where the variable can be referenced/used
  • There are four different variable scopes in PHP:
    local
    global
    static
    parameter

Local and global scope

  • Variables defined outside all functions, with global scope
  • Global variables can be accessed by any part of the script except functions
  • Variables declared inside PHP functions are local variables and can only be accessed inside functions
  • To access a global variable in a function, you need to use the globalkeyword
<?php
$x=5; // global variable

function myTest()
{
    $y=10; // local variable
    echo "<p>Testing variables within a function:<p>";
    echo "variable x by: $x";
    echo "<br>";
    echo "variable y by: $y";
} 

myTest();

echo "<p>Test out-of-function variable:<p>";
echo "variable x by: $x";
echo "<br>";
echo "variable y by: $y";
?>

Run Screenshot

Globalkeywords

  • The globalkeyword is used to access global variables within functions
  • To call global variables defined outside a function within a function, you need to precede the variables in the function with the global keyword
<?php
	$a = 10;
	$b = 20;
	$c = 30;
	function Text()
	{
		global $a,$b;
		echo $a;
		echo "<br>";
		echo $b;
		echo "<br>";
		echo $c;
	}

	text()
?>

Run Screenshot

Static Scope

  • When a function completes, all its variables are usually deleted
  • However, sometimes you want a local variable not to be deleted, you need to use the static keyword the first time you declare a variable
  • Note that this variable is still a local variable of the function
<?php
	function test(){
		static $x = 1;
		$y = 1;
		echo $x;
		echo "<br>";
		echo $y;
		$x++;
		$y++;
		echo "<hr>";
	}
	test();
	test();
	test();
	test();
?>

Run Screenshot

Parameter Scope

  • A parameter is a local variable that passes a value to a function by calling code
  • Parameters are declared in the parameter list as part of the function declaration
<?php 
	function text($a){
		echo $a;
	}

	text(10);
?>

Run Screenshot

Output Statement

  • There are two basic ways to output in PHP: echo and print
  • echo: can output one or more strings
  • print: Only one string is allowed to be output with a total return value of 1
  • Note: echo output is faster than print; Echo has no return value, print has return value 1

echo statement

  • Echo is a language structure that can be used with or without parentheses, echo or echo()
<?php 
	echo "<h2>PHP Very interesting!</h2>";
	echo "Hello world!<br>";
	echo "I want to learn PHP!<br>";
	echo "This is a", "Character string,", "Used", "Multiple", "Parameters.";
?>

Run Screenshot

print statement

  • Print is also a language structure that can use parentheses or not: print()
<?php 
	print "<h2>PHP Very interesting!</h2>";
	print "Hello world!<br>";
	print "I want to learn PHP!";
?>

Run Screenshot

Instructions for using EOF (heredoc)

  • PHP EOF is a method of defining a string in command-line shell s and program languages
    Overview of use
    • Must be followed by a semicolon, otherwise compilation fails
    • EOF s can be replaced by any other, just make sure the end and start identities match
    • The end identifier must be a top-level, exclusive line (that is, it must start at the beginning of the line and cannot be joined by any white space or characters)
    • Start tags can be unquoted or single double quoted, unquoted and consistent with double quoted effects, explaining embedded variables and escape symbols, single quoted but not embedded variables and escape symbols
    • When content requires embedded quotation marks (single or double quotation marks), no escape character is required, and the single and double quotation marks themselves are escaped, which is equivalent to the use of q and q Q here
<?php
echo <<<EOF
        <h1>My first title</h1>
        <p>My first paragraph.</p>
EOF;
// End requires a separate line and no space before or after
?>

Run Screenshot

data type

  • String (string)
  • Integer (Integer)
  • Float (Float)
  • Boolean (Boolean)
  • Array (array)
  • Object (Object)
  • NULL (null value)

NULL value

  • A NULL value means that a variable has no value, and NULL is a value of data type NULL
  • NULL value indicates whether a variable is null
  • You can empty variable data by setting the variable value to NULL
<?php
$x="Hello world!";
$x=null;
var_dump($x);
?>

Run Screenshot

Type comparison

  • Loose comparison: use two equal signs==comparison, compare values only, do not compare types
  • Strict comparison: use three equal signs===to compare, compare values, compare types
<?php
	if(42 == "42") {
	    echo '1,Equal Value';
	}
	 
	echo "<br>";

	if(42 === "42") {
	    echo '2,Equal type';
	} else {
	    echo '3,Types are not equal';
	}
?>

Run Screenshot

constant

  • A constant is an identifier for a simple value that cannot be changed in a script
  • A constant consists of letters, underscores, and numbers. Numbers do not start
  • Constant names do not need to be preceded by a $modifier
  • Note: Constants are available throughout the script (constants are global)

Set Constant

  • Setting constants using the define() function
  • Syntax: bool define (string $name, mixed $value [, bool $case_insensitive = false])
  • The function has three parameters: name: constant name; Value: The value of a constant, case_insensitive optional parameter, case sensitive by default
<?php

	define("GREETING", "Welcome to Runoob.com");
	echo GREETING;  
	
?>

Run Screenshot

Character string

  • String variables are used to store and process text
  • When assigning a text value to a variable, single or double quotes are required
<?php
	$a = "hello PHP";
	echo $a;
?>

Run Screenshot

Collocation Operator

  • In PHP, there is only one string operator
  • Collocation Operator (.) Role: Used to connect two string values
<?php
	$a = "hello";
	$b = "world";
	echo $a.$b;
	echo "<br>";
	echo $a."+++".$b;
?>

Run Screenshot

strlen() function

  • strlin(): calculates the string length
<?php
	echo strlen("hellophp");
?>

Run Screenshot

strpos() function

  • strpos(): Used to find a character or a specified piece of text within a string
  • Match to character, return the first matched character position
  • If it does not match, false is returned
<?php
	echo strpos("hellophp",'p');
?>

Run Screenshot

operator

-  Assignment operator:=
- Arithmetic operator:+
<?php 
$x=10; 
$y=6;
echo ($x + $y); // Output 16
echo '<br>';  // Line Break
 
echo ($x - $y); // Output 4
echo '<br>';  // Line Break
 
echo ($x * $y); // Output 60
echo '<br>';  // Line Break
 
echo ($x / $y); // Output 1.66666666667
echo '<br>';  // Line Break
 
echo ($x % $y); // Output 4
echo '<br>';  // Line Break
 
echo -$x;
?>

Assignment Operators

<?php 
$x=10; 
echo $x; // Output 10
 
$y=20; 
$y += 100;
echo $y; // Output 120
 
$z=50;
$z -= 25;
echo $z; // Output 25
 
$i=5;
$i *= 6;
echo $i; // Output 30
 
$j=10;
$j /= 5;
echo $j; // Output 2
 
$k=15;
$k %= 4;
echo $k; // Output 3
?>

Increment/Decrement Operators

<?php
$x=10; 
echo ++$x; // Output 11
 
$y=10; 
echo $y++; // Output 10
 
$z=5;
echo --$z; // Output 4
 
$i=5;
echo $i--; // Output 5
?>

Comparison operator

<?php
$x=100; 
$y="100";
 
var_dump($x == $y);
echo "<br>";
var_dump($x === $y);
echo "<br>";
var_dump($x != $y);
echo "<br>";
var_dump($x !== $y);
echo "<br>";
 
$a=50;
$b=90;
 
var_dump($a > $b);
echo "<br>";
var_dump($a < $b);
?>

Logical operators

  • and:
  • Or: or
  • xor: xor
  • &&: and
  • ||: or
  • !: wrong

Array Operations

<?php
$x = array("a" => "red", "b" => "green"); 
$y = array("c" => "blue", "d" => "yellow"); 
$z = $x + $y; // Combination of $x and $y numbers
var_dump($z);
var_dump($x == $y);
var_dump($x === $y);
var_dump($x != $y);
var_dump($x <> $y);
var_dump($x !== $y);
?>

Ternary operator

  • Grammar Format: (expr1)? (expr2): (expr3)
<?php
	$test = 'hellophp';
	// longhand
	$username = isset($test) ? $test : 'nobody';
	echo $username;
	 
	echo "<br>";
	$username = $test ?: 'nobody';
	echo $username;
?>

Run Screenshot

Conditional judgment statement if...

  • Conditional statements are used to perform different actions based on different conditions

if statement

Syntax: if {code to execute when the condition is established;}
Example

<?php
	$a = 10;
	if($a > 5){
		echo "hahahaha";
	}
?>

Run Screenshot

if...else statement

  • Execute one piece of code when the condition is true, and another statement when the condition is not.
  • Syntax: if {executes when the condition is established;} else{execute if condition is not established;}
  • Example:
<?php
	$t=100;
	if ($t<"20")
	{
	    echo "Have a good day!";
	}
	else
	{
	    echo "Have a good night!";
	}
?>

Run Screenshot

If...else if...else statement

  • Execute a block of code when one of several conditions is true
  • Syntax: if {executes when the condition is established;} Elseif {execute when condition is established;} Elseif {execute when condition is established;} else{execute if condition is not established;}
  • Example:
<?php
	$t = 50;
	if ($t < 10)
	{
	    echo "Have a good morning!";
	}
	elseif ($t < 20)
	{
	    echo "Have a good day!";
	}
	else
	{
	    echo "Have a good night!";
	}
?>

Run Screenshot

Conditional Judgment Statement Switch

  • Used to perform different actions based on different conditions
  • Syntax: switch(){}
  • Example:
<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
    echo "Your favorite color is red!";
    break;
case "blue":
    echo "Your favorite color is blue!";
    break;
case "green":
    echo "Your favorite color is green!";
    break;
default:
    echo "Your favorite color is not red, blue, Or green!";
}
?>

Run Screenshot

array

  • An array is a special variable that can store multiple values in a single variable

Create Array

  • array();
  • Array Type: Numeric Array, Associated Array, Multidimensional Array

Array of values

  • Two ways to create a numeric array
  • Automatically assign ID keys (ID keys always start at 0)$cars=array("Volvo","BMW","Toyota");
  • Manually assign ID key $cars[0]='Volvo'; $ Cars[1]='BMW'; $ Cars[2]= "Toyota";
  • Example:
<?php
$cars=array("Chengdu","Beijing","Nao");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

Run Screenshot

Gets the array length-count()

  • The count() function returns the length of the array (the number of elements)
  • Example:
<?php
	$cars=array("Chengdu","Beijing","Nao");
	echo count($cars);
?>

Run Screenshot

Array of variable values

  • Traverse and print all values in a numeric array
  • Example:
<?php
	$cars=array("Chengdu","Beijing","Nao");
	$arrlength=count($cars);
 
	for($x=0;$x<$arrlength;$x++)
	{
	    echo $cars[$x];
	    echo "<br>";
	}
?>

Run Screenshot

Associated Array

  • Associated arrays are arrays that use the specified keys assigned to the array by the user
  • There are two ways to create associative arrays:
  • $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
  • $age['Peter']="35"; $age['Ben']="37"; $age['Joe']="43";
  • Example:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>

Run Screenshot

Multidimensional Array

  • The values in one array can be another array, and the values of the other can also be an array. In this way, we can create two- or three-dimensional arrays
<?php
// Two-dimensional array:
$cars = array
(
    array("Volvo",100,96),
    array("BMW",60,59),
    array("Toyota",110,100)
);

Array sorting function

  • sort(): ascending the order of the array
  • rsort(): Descending the array
  • asort() - Arrays are sorted in ascending order based on the values of the associated array
  • ksort() - Arrays are sorted in ascending order according to the key of the associated array
  • arsort() - Arrays are sorted in descending order based on the values of the associated array
  • krsort() - Arrays are sorted in descending order according to the key of the associated array
<?php
	$numbers=array(4,6,2,22,11); 
	rsort($numbers); 
	print_r($numbers); 
?>

Run Screenshot

Super Global Variables

  • Several superglobals are predefined in PHP, which means they are available in all scopes of a script
  • $GLOBALS
  • $_SERVER
  • $_REQUEST
  • $_POST
  • $_GET
  • $_FILES
  • $_ENV
  • $_COOKIE
  • $_SESSION

while Loop

  • The while loop repeats the code block until the specified condition is not established
  • Syntax: while {executed code}
  • Example:
<?php
	$a = 0;
	while ($a < 5) {
		echo $a;
		echo "<br>";
		$a++;
	}
?>

Run Screenshot

do...while statement

  • Execute the code at least once, then check the conditions, and repeat the loop as long as the conditions are true
  • Syntax: do {statement to execute} while (condition)
  • Example:
<?php
	$a = 0;
	do{
		echo $a;
		echo "<br>";
		$a++;
	}
	while ($a < 6);
?>

Run Screenshot

for loop

  • for loops are used when the user knows beforehand how many times the script needs to be run
  • Syntax: for (initial value; condition; increment) {executed code}
  • Example:
<?php
	$a = 0;
	for(;$a < 10;$a++){
		echo $a;
		echo "<br>";
	}
?>

Run Screenshot

foreach loop

  • foreach loop is used to traverse arrays
  • Loop that outputs the value of a given array
  • Syntax: foreach($array as $value) {code to execute}
  • For each loop, the value of the current array element is assigned to the $value variable (the array pointer moves one by one), and you will see the next value in the array during the next loop.
  • Example:
<?php
	$x=array("Google","Runoob","Taobao");
	foreach ($x as $value)
	{
	    echo $value;
	    echo "<br>";
	}
?>

Run Screenshot

  • Loop that outputs a given array key and value
  • Syntax: foreach ($array as $key => $value) {code to execute}
  • Example:
<?php
	$x=array("Google","Runoob","Taobao");
	foreach ($x as $key => $value){
 		echo "key  by " . $key . "´╝îCorresponding value by ". $value;
 		echo "<br>";
	}

?>

Run Screenshot

function

  • In PHP, more than 1,000 built-in functions are provided

Create function

  • Functions are executed by calling functions
  • Syntax: function functionName() {code to execute}
  • Function naming guidelines: Names should indicate what they do, and function names begin with a letter or an underscore
  • Example:
<?php
	function writeName(){
		echo "my name is haha";
	}
	writeName();
?>

Run Screenshot

Adding parameters in a function

  • Example:
<?php
	// A parameter value needs to be passed in
	function writeName($name){
		echo "my name is $name";
		echo "<br>";
	}
	
	// Two parameter values need to be passed in
	function writeCar($car,$id){
		echo "My car is $car,License plate number is $id";
	}

	writeName('hello');
	writeCar("Neck 30+","Beijing A666666");
?>

Run Screenshot

Return value

  • To have a function return a value, use the return statement
<?php
	function add($a,$b){
		$res = $a + $b;
		return $res;
	}
	echo " 10 + 20 =" . add(10,20) ;
?>

Run Screenshot

magic constant

  • PHP provides a large number of predefined constants to any script it runs
  • However, many constants are defined by different extension libraries and only occur when they are loaded, either dynamically loaded, or already included at compile time.
  • There are eight magic constants whose values change as they change in the code

LINE

  • Returns the current line number in the file
  • Example:
<?php
	echo "This is the first" . __LINE__ . "That's ok";
?>

Run Screenshot

FILE

  • Full path and file name of the file
  • If used in an included file, the included file name is returned
  • Example:
<?php
	echo "This file is located in '" . __FILE__ . "'";
?>

Run Screenshot

DIR

  • The directory where the file is located
  • If used in included files, returns the directory where the included files are located
  • Example:
<?php
	echo "This file is located in '" . __DIR__ . "'";
?>

Run Screenshot

FUNCTION

  • Returns the name of the function in which it is located
  • Example:
<?php
	function test(){
		echo "Function name:" . __FUNCTION__;
	}
	test();
?>

Run Screenshot

CLASS

  • Returns the name of the class in which it resides
  • Example:
<?php
	class test{
		function t(){
			echo "Class name:" . __CLASS__;
			echo "<br>";
			echo "Function name:" . __FUNCTION__;
		}
	}
	$a = new test();
	$a -> t();
?>

Run Screenshot

TRAIT

  • Name of Trait
  • Example:
<?php
class Base {
    public function sayHello() {
        echo 'Hello ';
    }
}
 
trait SayWorld {
    public function sayHello() {
        parent::sayHello();
        echo 'World!';
    }
}
 
class MyHelloWorld extends Base {
    use SayWorld;
}
 
$o = new MyHelloWorld();
$o->sayHello();
?>

Run Screenshot

METHOD

  • Method name of class
  • Returns the name of the method when it was defined
  • Example:
<?php
function test() {
    echo  'The function name is:' . __METHOD__ ;
}
test();
?>

Run Screenshot

NAMESPACE

  • Name of the current namespace
  • Example:
<?php
	namespace MyProject;
	 
	echo 'The namespace is:"', __NAMESPACE__, '"';
?>

Run Screenshot

Namespace

  • Namespaces solve two types of problems:
  • User-written code has name conflicts with classes/functions/constants or third-party classes/functions/constants within PHP
  • Create aliases for long identifier names

Defining namespaces

  • By default, all constants, classes, and function names are placed under the global control, just as they were before the PHP-supported namespaces
  • Namespace must be the first statement in a program script
  • Namespaces are declared by the keyword namespace
  • If a file contains a namespace, it must declare the namespace before all other code
  • Syntax: <? PHP //Define the code namespace MyProject in the'MyProject'namespace;

Namespace use

  • Unqualified name, or class name without prefix
  • Qualified name, or include prefix name
  • Fully qualified name, or name containing global prefix operator

Use Naming Control: Alias/Import

  • Import/use aliases using the use operator
  • Include multiple use statements in one line
  • Import and dynamic name

Object-oriented

  • In Object-oriented programming (abbreviation: OOP)
  • Objects are a whole of information and descriptions of how it is handled, and are abstractions of the real world.
    The three main characteristics of an object
    • Behavior of the object: What actions can be applied to the object, turning the light on or off is behavior
    • The shape of the object: how the object responds when applied, color, size, appearance
    • Representation of an object: The representation of an object is equivalent to an identity card, which distinguishes what is different in the same behavior and state.
      For example, Animal is an abstract class, we can be specific to a dog and a sheep, and dog and sheep are specific objects, they have color attributes, can write, can run and other behavior states

Object-Oriented Content

  • Class: Defines the abstract characteristics of a thing
  • Object: Instance of class
  • Member variable: A variable defined within a class that can be accessed through a member function and called an object's property when the class is instantiated as an object
  • Member function: Defined within a class and used to access data for objects
  • Inheritance: A mechanism by which subclasses automatically share parent data structures and methods, which is a relationship between classes
  • Parent class: A class is inherited by other classes and is called a parent class, a base class, a superclass
  • Subclass: A class inherits other classes, called a subclass or derived class
  • Polymorphism: The same function or method works on many types of objects and produces different results. Different objects can produce different results when they receive the same message. This phenomenon is called polymorphism.
  • Overload: When a function or method has the same name but different parameter lists
  • Abstract: Objects with consistent data structures (attributes) and behaviors (operations) are abstracted into classes
  • Encapsulation: Binding the attributes and behaviors of an object in the real world and placing them in a logical unit
  • Constructor: Used to initialize objects when they are created, that is, to assign initial values to object member variables. Always used with the new operator to initialize objects when they are created in statements that create objects. That is, to assign initial values to object member variables. Always used with the new operator in statements that create objects.
  • Destructors: Destructors, in contrast to constructors, automatically execute destructors when an object ends its life cycle, such as when the function in which the object resides has been called
  • Destructors are often used to do the cleanup job

Class Definition

  • Class uses the class keyword followed by a class name definition
  • Variables and methods can be defined within {} after the class name
  • Class variables are declared with var, and variables can also initialize values
  • Function definitions are similar to those of PHP functions, but functions can only be accessed through the class and its instantiated objects
  • Example:
<?php
	class Site {
		// Member variables
		var $url;
		var $title;

		//Member function
		function setUrl($par){
			$this->url = $par;  //Variable $this represents its own object
		}

		 function getUrl(){
     		echo $this->url;
     		echo "<br>";
  		}

  		function setTitle($par){
  			$this->title = $par;
  		}

  		function getTtile(){
  			echo $this->title;
  			echo "<br>";
  		}
	}
?>

create object

  • Instantiate objects of this class using the new operator
  • Example:
<?php
	class Site {
		// Member variables
		var $url;
		var $title;

		//Member function
		function setUrl($par){
			$this->url = $par;  //Variable $this represents its own object
		}

		 function getUrl(){
     		echo $this->url;
     		echo "<br>";
  		}

  		function setTitle($par){
  			$this->title = $par;
  		}

  		function getTtile(){
  			echo $this->title;
  			echo "<br>";
  		}
	}
	$a = new Site;
	$b = new Site;
	$c = new Site;
?>

Call member methods

  • The member method is invoked using the object, and the member method of the object can only operate on the member variables of the object
  • Example:
<?php
	class Site {
		// Member variables
		var $url;
		var $title;

		//Member function
		function setUrl($par){
			$this->url = $par;  //Variable $this represents its own object
		}

		 function getUrl(){
     		echo $this->url;
     		echo "<br>";
  		}

  		function setTitle($par){
  			$this->title = $par;
  		}

  		function getTtile(){
  			echo $this->title;
  			echo "<br>";
  		}
	}

	// create object
	$a = new Site;
	$b = new Site;
	$c = new Site;

	// Call member functions, set title and url
	$a->setTitle("Genuine Vegetable");
	$b->setTitle("hello");
	$c->setTitle('world');

	$a->setUrl('www.cai.com');
	$b->setUrl('www.hello.com');
	$c->setUrl('www.world.com');

	// Call member variable to get title and url
	$a->getTtile();
	$b->getTtile();
	$c->getTtile();

	$a->getUrl();
	$b->getUrl();
	$c->getUrl();
?>

Run Screenshot

Constructor

  • Primarily used to initialize objects when they are created, that is, to assign initial values to object member variables
  • Use with the new operator in statements that create objects
  • Syntax: `void u Construct ([mixed $args [, $...]])
  • Example:
<?php
	class Site {
		// Member variables
		var $url;
		var $title;

		function __construct( $par1, $par2 ) {
		    $this->url = $par1;
		    $this->title = $par2;
		  }
		 	  	function setTitle($par){
	  			$this->title = $par;
	  		}

	  	function getTtile(){
	  			echo $this->title;
	  			echo "<br>";
	  		}
	}
	// create object
	$a = new Site("Genuine Vegetable",'www.cai.com');
	$b = new Site("hello",'www.hello.com');
	$c = new Site('world','www.world.com');
		// Call member variable to get title and url
	$a->getTtile();
	$b->getTtile();
	$c->getTtile();

	$a->getUrl();
	$b->getUrl();
	$c->getUrl();
?>

Run Screenshot

Destructor

  • Destructors, in contrast to constructors, automatically execute destructors when an object ends its life cycle, such as when the function in which the object resides has been called
  • Syntax: void u Destruct (void)

inherit

  • Use the keyword extends to inherit a class, PHP does not support multiple inheritance
  • Syntax: class Child extends Parent {//code part}
  • Example:
<?php
	class Site {
		// Member variables
		var $url;
		var $title;

		//Member function
		function setUrl($par){
				$this->url = $par;  //Variable $this represents its own object
			}

		function getUrl(){
	     		echo $this->url;
	     		echo "<br>";
	  		}

	  	function setTitle($par){
	  			$this->title = $par;
	  		}

	  	function getTtile(){
	  			echo $this->title;
	  			echo "<br>";
	  		}
	}

	//inherit
	class Child_Site extend Site{
		 var $category;

	    function setCate($par){
	        $this->category = $par;
	    }
	  
	    function getCate(){
	        echo $this->category . PHP_EOL; //PHP_EOL Line Break
	    }
	}

?>

override

  • If the method inherited from the parent does not meet the needs of the subclass, it can be overridden, a process called override, also known as override of the method
  • Example:
<?php
	class Site {
		// Member variables
		var $url;
		var $title;

		//Member function
		function setUrl($par){
				$this->url = $par;  //Variable $this represents its own object
			}

		function getUrl(){
	     		echo $this->url;
	     		echo "<br>";
	  		}

	  	function setTitle($par){
	  			$this->title = $par;
	  		}

	  	function getTtile(){
	  			echo $this->title;
	  			echo "<br>";
	  		}
	}

	//inherit
	class Child_Site extend Site{

		// Overwrite
		function getTtile(){

		}

		function setTitle(){

		}
	}

?>

access control

PHP controls access to properties or methods by adding the keywords public, protected, or private before them

  • public: public class members can be accessed anywhere.
  • protected: protected class members can be accessed by themselves, their children, and their parents.
  • private: private class members can only be accessed by the class in which they are defined.

Access control for properties

  • Class properties must be defined as public, protected, or private. If defined by var, it is considered public

Method Access Control

  • Methods in classes can be defined as public, private, or protected. If these keywords are not set, the method defaults to public

Interface

  • Using interface s, you can specify which methods a class must implement, but you don't need to define the specific content of those methods
  • Defined by the interface keyword, where all methods defined are empty
  • All methods defined in an interface must be public, which is a property of the interface
  • To implement an interface, use the implements operator
  • All methods defined in the interface must be implemented in the class
  • Classes implement multiple interfaces and use commas to separate the names of multiple interfaces
  • Grammar:
// Declare Interface
interface name{}

// Implement Interface
class className implements name{}

constant

  • Define values that remain constant throughout a class as constants
  • You do not need the $symbol to define and use constants
  • The value of a constant must be a fixed value, not a variable, a class property, the result of a mathematical operation, or a function call
  • A variable can be used to dynamically invoke a class. However, the value of the variable cannot be a keyword (such as self, parent, or static)
  • Define Constant Keyword const

abstract class

  • Any class in which at least one method is declared abstract must be declared abstract
  • Classes defined as abstract cannot be instantiated
  • When inheriting an abstract class, the subclass must define all the abstract methods in the parent class, and their access control must be the same as in the parent class.
  • Use the keyword abstract
  • Subclass methods can contain optional parameters that do not exist in parent abstract methods

static keyword

  • Declaring a class property or method as static allows direct access without instantiating the class
  • Static properties cannot be accessed through a class of instantiated objects (but static methods can)
  • Pseudo variable $this is not available in static methods because static methods do not require objects to be called
  • Static properties are not accessible by objects through the ->operator
  • Use a variable to dynamically invoke the class. However, the value of the variable cannot be the keyword self, parent, or static

final keyword

  • If a method in the parent class is declared final, the subclass cannot override the method
  • If a class is declared final, it cannot be inherited

Call parent class construction method

  • PHP does not automatically call the parent class's construction method in the child class's construction method
  • To execute the parent class's construction method, you need to call parent::u in the child class's construction method Construct()
  • Example:
<?php
class BaseClass {
	   function __construct() {
	       print "BaseClass Construction methods in classes" . PHP_EOL;
	   }
	}
	class SubClass extends BaseClass {
	   function __construct() {
	       parent::__construct();  // Subclass construction methods cannot automatically call parent class construction methods
	       print "SubClass Construction methods in classes" . PHP_EOL;
	   }
	}
	class OtherSubClass extends BaseClass {
	    // Construct method inheriting BaseClass
	}

	// Call BaseClass construction method
	$obj = new BaseClass();

	// Call BaseClass, SubClass construction method
	$obj = new SubClass();

	// Call BaseClass construction method
	$obj = new OtherSubClass();
?>

Run Screenshot

Topics: PHP Class for while