Php 如何仅在第一个类中而不是在继承对象中使用session_start()
我在这里遇到了问题,以下是示例代码:Php 如何仅在第一个类中而不是在继承对象中使用session_start(),php,oop,Php,Oop,我在这里遇到了问题,以下是示例代码: class example { public function __construct() { session_start(); echo "this is from example class"; } } class example2 extends example { public function __construct(){ echo "this is form example2 class"
class example {
public function __construct() {
session_start();
echo "this is from example class";
}
}
class example2 extends example {
public function __construct(){
echo "this is form example2 class";
}
}
$example = new example(); // until here, no error.
// Output: this is form example class
$example2 = new example2() // here, I get error
// Output: this is form example class
// Output: Notice: A session had already been started - ignoring session_start()
// Output: this is from example2 class
那么,如何解决这个问题呢?如何在示例类中忽略session_start(),以便在example2类中session_start()不再运行。您需要调用
父类::_construct()
,就像在第二个类中一样
class example {
public function __construct() {
if(!isset($_SESSION)){
session_start();
}
echo "this is from example class";
}
}
class example2 extends example {
public function __construct(){
parent::__construct(); // add this line
echo "this is form example2 class";
}
}
$example = new example(); // until here, no error.
// Output: this is form example class
$example2 = new example2() // here, I get error
// Output: this is form example class
// Output: Notice: A session had already been started - ignoring session_start()
// Output: this is from example2 class
您可以在实用程序类中定义会话的开始,或者使用
if(isset($\u session['a\u var\u registed\u to\u your\u sess'))…
检查会话是否存在。有关更多信息,请参阅:如果您的课程的目的不是管理会话,那么它不是任何session.*
函数的合适位置。阅读。错误:注意:会话已启动-忽略会话\u start()已编辑。见头等舱。