php中construct(php __construct 是不是每个方法都会加载)

本文目录
php __construct 是不是每个方法都会加载
不是,只有你每次new这个类生成对象的时候,才会加载__construct,等于给你这个对象加点料.
这个类本身是不加载的,只有我$userModel = new User();才会触发.
第一种写法更规范一些.构造函数通常只写一些全局通用的.
php __construct 传参问题
$std = new student(100);//传入scores
另外student的构造函数应该这样写
function __construct($num)
{
parent::__construct(’someone’,24,’123445’);//调用父类的构造函数完成初始化
$this-》scores = $num;
}
至于父类的构造函数参数可以从student类传进来,像这样
function __construct($name,$age,$tel,$num)
或者只有一个参数的话使用数组传入,像这样
function __construct($arg)
{
parent::__construct($arg);//调用父类的构造函数完成初始化
$this-》scores = $arg;
}
echo $stu-》name;//这句为什么打印不出来?
是$std吧?
php构造方法对成员变量赋值 function__construct
function __construct
function 是系统关键词,表示定义一个方法,后面加空格然后根方法名( __construct
是方法名)。你的未加空格
__construct 是系统内置的,叫魔术方法,每次实例化类是会自动执行此方法。
还有就是调用类的成员变量不需要在变量前面加 $ 比如:
$this-》school_name = $name; 正确
$this-》$school_name = $name; 错误
《?php
class School {
public $school_name;
public $school_student;
public $school_room;
public $school_teacher;
function __construct($name, $student, $room, $teacher) {
$this-》school_name = $name;
$this-》school_student = $student;
$this-》school_room = $room;
$this-》school_teacher = $teacher;
}
function show() {
echo "!@#$%^&*";
}
}
class People extends School {
public $teachername;
function __construct($tname, $studentconsts) {
$this-》teachername = $tname;
$this-》school_student = $studentconsts;
}
function show() {
return "今天上课" . $this-》teachername . "讲课,学生" . $this-》school_student . "人";
}
}
class Tongji extends School {
function show() {
return "学校名:" . $this-》school_name . "学生数:" . $this-》school_student . "教室数:" . $this-》school_room . "教师数:" . $this-》school_teacher;
}
}
$a = new People ( "周周周", 20 );
$b = new School ( "DZ", 20, 50, 2 );
echo $a-》show () . "《br》";
echo $b-》show ();
?》

更多文章:
全球新冠肺炎疫情背景下航运发展(盐田港复苏日志:半年历劫从“低谷”到“爆仓” 疫情之后巨轮如何越洋航行)
2026年9月7日 17:10
matlab求解带字母参数方程组(我想matlab求一个关于x,y的方程组 ab c d f e h m n 都是参数)
2026年9月7日 16:30
oracle中的循环语句(下面哪个不是oracle程序设计中的循环语句 a for)
2026年9月7日 15:30
电脑里2个系统怎么删除一个(电脑开机显示有两个系统,如何删除一个)
2026年9月7日 12:20
scrollthrough意思(“scroll”是什么意思)
2026年9月7日 08:00
怎么激活keygen(注册机如何激活cad2008一个简单激活cad2008的方法)
2026年9月7日 06:30




