php – 初始化类变量的更好方法
发布时间:2020-12-13 17:42:53 所属栏目:PHP教程 来源:网络整理
导读:我一直在寻找一段时间,但我找不到答案,这两种方式在 PHP中使用变量类的内容有什么区别?:(如果有的话) class MyClass{ private $myVariable='something'; public function __construct() { }}class MyClass{ private $myVariable; public function __constru
我一直在寻找一段时间,但我找不到答案,这两种方式在
PHP中使用变量类的内容有什么区别?:(如果有的话)
class MyClass { private $myVariable='something'; public function __construct() { } } class MyClass { private $myVariable; public function __construct() { $this->myVariable='something'; } } 解决方法
看这个场景:
class Parent { protected $property1; // Not set protected $property2 = '2'; // Set to 2 public function __construct(){ $this->property1 = '1'; // Set to 1 } } // class Parent; class Child extends Parent { public function __construct(){ // Child CHOOSES to call parent constructor parent::__construct(); // optional call (what if skipped) // but if he does not,->property1 remains unset! } } // class Child; 这是两个电话之间的差异. parent :: __ construct()对于从父级继承的子类是可选的.所以: >如果您有标量(如在is_scalar()中)需要预设的属性,请在类定义中执行此操作以确保它们也存在于子类中. 这一切都取决于您如何设计代码的功能. 这里没有错,它只适合你. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |