【问题标题】:PHP Protected variables don't work for mePHP 保护变量对我不起作用
【发布时间】:2017-08-21 22:53:16
【问题描述】:

我在使用 PHP 中的受保护变量时遇到问题。为什么这段代码不起作用?它一直显示错误 500。这是代码:

<?php
class A
{
    protected $variable;
}

class B extends A
{
    $this->variable = 'A';
}
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
        <!-- Code -->
    </body>
</html>

谢谢

【问题讨论】:

  • 去掉$this-&gt;variable = 'A'或者在方法中添加这个语句。
  • 我无权访问 php.ini。
  • ini_set('error_reporting', E_ALL); ini_set("display_errors", 1);
  • $this-&gt;variable = 'A'; 需要在方法中

标签: php variables protected


【解决方案1】:

类变量应该在方法或函数中使用。

<?php
class A
{
    protected $variable;
}

class B extends A
{
    // Class variables need to be used within methods. 
    // For example: to set the value
    function ConnectToDatabase()
    {
        $this->variable = 'mysql:user;pwd:12345';
    }

    // or to return the value
    function output()
    {
        return $this->variable;
    }
}

$b = new B();

$b->connectToDatabase();

echo $b->output();

http://sandbox.onlinephpfunctions.com/code/ac3171a98ccb901ca7cc8890659ca409a47fb30c

【讨论】:

    【解决方案2】:

    用以下代码替换你的 php 代码:

    <?php
    
    error_reporting(-1);
    
    class A
    {
        protected $variable;
    }
    
    class B extends A
    {
        public function __construct()
        {
            $this->variable = 'A';
        }
    }
    
    ?>
    

    它应该可以解决问题,如果还有其他问题,可以为您提供有关正在发生的事情的更详细信息。

    【讨论】:

    • 他也可以重新申报财产。
    • 您的构造函数声明中还缺少function。
    • @bassxzero 他还可以创建一个不扩展 A 或在不同范围内使用 $variable 或根本没有类的新类。我认为为问题提供近乎无限的解决方案并不是特别有用/必要的。虽然缺少 function 关键字,但很好。
    【解决方案3】:

    您不能在课程正文中放置诸如归因之类的说明。仅允许成员定义。将$this-&gt;variable = 'A'; 放入方法中。

    变化:

    class B extends A
    {
        $this->variable = 'A';
    }
    

    收件人:

    class B extends A
    {
        public function __construct(){
            $this->variable = 'A';
        }
    }
    

    【讨论】:

    • 他也可以重新申报财产。
    • @bassxzero 为什么要重新声明?
    • 因为在运行时设置变量值可能不是他想要的行为。他可能想要一种“默认值”类型的行为。
    猜你喜欢
    • 2013-08-10
    • 1970-01-01
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多