php基础入门

Jun 23, 2016 pm 01:08 PM

一、序言

 由于新公司的需要,我也就从原来的asp专向了,php的学习中。希望通过自己的学习能够尽快的熟悉了解php

二、php独特的语法特色

 1、引号问题

在php中单引号和双引号的作用基本相同,但是有些场合却又是不同的

都可以用来包含要引用字符串

<meta charset="utf-8"><?php    $str1="xiecanyong";    $str2='xcy';    echo $str1;    echo "<br />";    echo $str2;?>
Copy after login

但是单引号中的内容只被解析成为字符串,而双引号可以在字符串中加入变量

<meta charset="utf-8"><?php    $age=",I am age 22";    $str1="xiecanyong$age";    $str2='xcy$age';    echo $str1;    echo "<br />";    echo $str2;?>
Copy after login

结果就自行运行一下,这里不解释

2、PHP常量

PHP相比于ASP,存在一些系统封装好的常量,这些有利于我们的使用,同时还支持我们自行封装常量

常见的常量有:

如下一些常用的PHP系统常量:

__FILE__ 当前PHP文件名

__LINE__ 当前PHP文件中所在的行数

__FUNCTION__ 当前所执行的函数

__CLASS__ 当前所执行的类

PHP_VERSION PHP的版本

PHP_OS 当前服务器的操作系统

TRUE 同true

FALSE 同false

E_ERROR 到最近的错误处

E_WARNING 到最近的警告处

E_PARSE 语法有错误处

E_NOTICE PHP语言中有异常处

M__PI 圆周率

M__E 科学常数e

M__LOG2E 以2为底e的对数

M_LOG10E 以10为底e的对数

M_LN2 2的自然对数

M_LN10 10的自然对数

PHP系统常量的内容就介绍到这里,希望对大家有所帮助。

举个例子:

<meta charset="utf-8"><?php    echo __Line__;?>
Copy after login

打印出来的结果是:3,表示当前是在第三行执行

在常量的使用中,我们一般是这样使用的

1、使用define方法来定义

<meta charset="utf-8"><?php    //模拟圆的面积计算    define("R", 5);    $area=R*R*pi();    echo $area;?>
Copy after login

2、使用const关键字来定义
例如:const p=2;这样就确定了一个常量p,值为2

3、常量的检验

对于一个大型项目而言,我们不知道某个参数是否为变量还是常量,如果是常量的话,那么重新赋值会发生错误,所以我们要通过defined方法来检验是否为某个参数是否为常量

<meta charset="utf-8"><?php    //$CONSTANT="2";    define("CONSTANT","2");if (defined('CONSTANT')) {    echo CONSTANT;}?>
Copy after login

3、PHP字符串操作

下面以一个综合的PHP字符串操作来讲解一下

<meta charset="utf-8"><?php    $str = "Hello PHP";    //获取指定字符在字符串中的位置    echo  strpos($str,"P")."<br>";    //截取指定位置的字符串(从第2个字符到最后)    $str1 = substr($str,2);    //截取指定位置的字符串(从第2个字符开始往后截取3位)    $str2 = substr($str,2,2);    //以指定间距分割字符串    $str3 = str_split($str);    $str4 = str_split($str,2);    print_r($str4)."<br>";    //以指定字符分割字符串    $str = "PHP JAVA JS HTML CSS";    $str5 = explode(" ",$str);    print_r($str5)."<br>";?>
Copy after login

字符串连接符

这里的字符串连接符跟其他语言的连接符有些不同,是通过"."来起到连接的,而在PHP中.=相当于其他语言的+=

错误控制运算符

PHP中提供了一个错误控制运算符“@”,对于一些可能会在运行过程中出错的表达式时,我们不希望出错的时候给客户显示错误信息,这样对用户不友好。表达式所产生的任何错误信息都被存放在变量$php_errormsg中,此变量在每次出错时都会被覆盖,所以如果想用它的话必须尽早检查。

<?php  $conn = @mysql_connect("localhost","username","password");echo "出错了,错误原因是:".$php_errormsg;?>
Copy after login

error_reporting(0); 禁止显示PHP警告提示

更多的字符串操作详见:http://www.jianshu.com/p/91ed5dc67977

4、可变函数

<meta charset="utf-8"><?php    function name(){        echo "xcy";    }    $n="name";    $n();?>
Copy after login

原理是:首先定义个一个name方法,然后是定义一个变量内容为name,最后一句其实就是$n()=name+(),也就是相当于执行了name这个方法

5、常见的内置函数

str_replace 可以实现字符串的替换

function_exists 判断一下函数是否存在

method_exists 可以用来检测类的方法是否存在

class_exists类是否定义可以使用

6、PHP面向对象

一个简单的PHP面向对象

<meta charset="utf-8"><?php    //定义一个类    class Person{        //定义一个属性        public $name="liLei";        //定义一个方法        public function Hobby(){            return $this->name;        }    }<br />  //实例化    $per=new Person();    $per->name='xiaoLi';    echo $per->Hobby();?>
Copy after login

特别注意->后面的变量不能加上"$"

一般我们常见的有public、private、protected这三个修饰符

要注意的是方法和属性也可以被static修饰,但是被修饰的方法或者是属性不可以使用->来调用,应该要换成::

<meta charset="utf-8"><?php    //定义一个类    class Person{        //定义一个属性        static $name="LiLei";    }    error_reporting(0);    $per=new Person();    $per::name;?>
Copy after login

构造函数

在PHP中也存在构造函数,但是书写上与asp有些不通过

<meta charset="utf-8"><?php    //定义一个构造类    class Person{        public function __construct(){            echo "this is construct";        }    }    $per=new Person();?>
Copy after login

如果是继承关系中,子类可以通过parent::__construct()来调用父类的构造函数

<meta charset="utf-8"><?php    //定义一个构造类    class Person{        public function __construct(){            echo "父类构造函数\n";        }    }    class LiLei extends Person{        public function __construct(){            parent::__construct();            echo "子类构造函数\n";                    }    }    $per=new LiLei();?>
Copy after login

在static方法中,不允许使用$this来对自身的调用,应该要写成self,同时我们应该还要注意::这个符号后面的$是不能省略的

<meta charset="utf-8"><?php    //定义一个构造类    class Person{        public function __construct(){            echo "父类构造函数\n";        }    }    class LiLei extends Person{                public function __construct(){            parent::__construct();            echo "子类构造函数\n";                    }        public static $name='LiLei';        public static function GoodAt(){            return self::$name;        }    }    $per=new LiLei();    echo "<br />";    echo $per::GoodAt();?>
Copy after login

_destruct(),这个方法为析构函数,但是由于PHP中存在垃圾回收机制,所以这个不常用

重载

这里的重载跟C#中方法的重载不是同一个定义,这里的重载指的是,对属性的相关操作

class Car {  private $ary = array(); //创建属性  public function __set($key, $val) {     $this->ary[$key] = $val;  }  //获取属性  public function __get($key) {      if (isset($this->ary[$key])) {          return $this->ary[$key];      }      return null;  }  //判断属性是否存在  public function __isset($key) {      if (isset($this->ary[$key])) {          return true;      }      return false;  }  //释放属性  public function __unset($key) {      unset($this->ary[$key]);  }}$car = new Car();$car->name = '汽车';  //name属性动态创建并赋值echo $car->name;
Copy after login

方法的重载通过 call 来实现,当调用不存在的方法的时候,将会转为参数调用call方法,当调用不存在的静态方法时会使用 __callStatic 重载。

class Car {  public $speed = 0;  public function __call($name, $args) {      if ($name == 'speedUp') {          $this->speed += 10;      }  }}$car = new Car();$car->speedUp(); //调用不存在的方法会使用重载echo $car->speed;
Copy after login

 

其他高级的操作详见:http://www.jianshu.com/p/26ac93b6bf32

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1270
29
C# Tutorial
1250
24
Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

See all articles