一、php常用的五种字符串函数
1. strpos()
功能:查找一个字符串在另一个字符串中第一次出现的位置。
参数:strpos(string $haystack, mixed $needle [, int $offset = 0])
返回值:返回needle在haystack中第一次出现的位置。如果没找到,返回false。
用法示例:
```
$str = "Hello world!";
$pos = strpos($str,"world");
if ($pos === false) {
echo "Sorry, world is not found in the string.";
} else {
echo "world found at position " . $pos;
}
```
2. strlen()
功能:返回一个字符串的长度。
参数:strlen(string $string)
返回值:返回字符串的长度。
用法示例:
```
$str = "Hello world!";
$len = strlen($str);
echo "The length of the string is " . $len;
```
3. substr()
功能:返回字符串的一部分。
参数:substr(string $string , int $start [, int $length])
返回值:返回字符串的一部分。
用法示例:
```
$str = "Hello world!";
$sub = substr($str, 0, 5);
echo "The substring is " . $sub;
```
4. str_replace()
功能:替换字符串中的一部分。
参数:str_replace(mixed $search, mixed $replace, mixed $subject [, int &$count])
返回值:返回替换后的字符串。
用法示例:
```
$str = "Hello world!";
$str = str_replace("world", "php", $str);
echo "The new string is " . $str;
```
5. strtolower()
功能:将字符串转换成小写。
参数:strtolower(string $string)
返回值:返回小写后的字符串。
用法示例:
```
$str = "Hello world!";
$str = strtolower($str);
echo "The new string is " . $str;
```
二、php 父类
在 PHP 中,每个类都有一个父类,我们称之为基类(base class)或超类(super class)或父类(parent class)。
PHP 中有一个预定义的父类叫做 stdClass,所有未声明父类的类都默认继承该类。
我们可以使用 extends 关键字来实现自定义类继承父类,例如:
```
class ChildClass extends ParentClass {
// 代码
}
```
三、构造函数
当我们创建一个类的对象时,自动调用的函数被称为构造函数(Constructor)。
构造函数的名称和类的名称相同,且不需要任何参数。
构造函数的主要作用是初始化对象的属性,使得对象可以通过创建实例自动进行初始化,例如:
```
class MyClass {
public $name;
function __construct() {
$this->name = "MyClass";
}
}
$obj = new MyClass;
echo $obj->name; // 输出:MyClass
```
当我们创建 MyClass 的实例 $obj 时,会自动调用 __construct() 方法来初始化对象 $obj 的属性。
注意:如果我们未显示定义 __construct() 方法,PHP 会在实例化对象时自动调用默认的构造函数。 如果你喜欢我们三七知识分享网站的文章, 欢迎您分享或收藏知识分享网站文章 欢迎您到我们的网站逛逛喔!https://www.ynyuzhu.com/
发表评论 取消回复