【问题标题】:OO PHP Array values are lost or missingOO PHP 数组值丢失或丢失
【发布时间】:2016-08-31 16:05:04
【问题描述】:

我对 OO PHP 还是比较陌生,坦率地说,我对 PHP 是比较陌生的。我有一个类,我在构造函数中分配数组值。但是,当我稍后访问该数组时,它告诉我该数组为空。任何想法这是如何超出范围的?

class SentenceContentContainer {
    public $strSentence; //theSentence entered
    public $arrayOfWords = []; //words in the sentence
    private $num_words_in_sentence; 

    function __construct($strSentence)
    {
        $this->strSentence = $strSentence;
        $arrayOfWords = explode(" ", $strSentence); //get the array of words in the string
        $num_words_in_sentence = count($arrayOfWords); //count elements in the sentence
    }

    function sortHighestLetterRepeaterOfSentence()
    {
        usort($arrayOfWords, "compare"); //says parameter 1 is null
    }
...
}

访问地址:

<html>
<head><title>PHP Code</title></head>
<body>
<?php

     include "classes.php";

     //process the data input
     $post_string = implode("",$_POST); //change post array to string
     // instantiate 1 of 2 objects
     $sentenceCC = new SentenceContentContainer($post_string);

     call_user_method("sortHighestLetterRepeaterOfSentence",$sentenceCC);
     ?>
<form method="post" action="">
<input type="text" name="value">
<input type="submit">
</form>

</body>
</html>

当我尝试在句子构造器中添加 this->arrayOfWords 时,它说这是一个语法问题。

我想知道问题是否在于它在输入句子后以某种方式运行 call_user_method,即使我还没有在表单中点击提交?我不会认为它会到达那里吗?

添加:当我在浏览器中调用脚本时,在我点击表单中的提交之前,是我看到警告消息的时候。
还添加:也许我需要检查 $arrayOfWords 是否为空或 sortHighestLetterRepeaterOfSentence 中的内容?我尝试添加对 null 的检查,但它说的是未定义的变量 arrayOfWords,我在其中测试它!= null。我也在考虑isset,但不清楚这是否能解决问题。

【问题讨论】:

  • 为什么不$sentenceCC-&gt;sortHighestLetterRepeaterOfSentence()?是的,$this 是必需的。

标签: php html arrays scope


【解决方案1】:

$arrayOfWords 是一个只存在于__construct 函数内部的变量。

$this-&gt;arrayOfWords 是一个私有类变量,存在于类的任何方法中,并且每个实例具有不同的值。

附:你为什么使用call_user_method?此函数已弃用(我认为在 PHP 7 中已删除)。只是一个简短的说明,如果您在教程中看到了这一点,您应该考虑一个新的教程,因为它会过时。

你可以这样做:

$sentenceCC->sortHighestLetterRepeaterOfSentence()

如果必须,您可以改用call_user_func

call_user_func([$sentenceCC, 'sortHighestLetterRepeaterOfSentence']);

【讨论】:

  • 你是说如果我想在构造函数中添加到arrayOfWords并稍后在其他函数中使用它,我需要使用$this->arrayOfWords来分配它吗?我不清楚。
  • @Michele:是的。您需要在类的每个方法中使用$this-&gt;arrayOfWords,包括构造函数。在构造函数中,你可以设置它的值。
【解决方案2】:

是的,即使没有提交表单,这段代码也会执行。

我认为你应该检查 $_POST 变量并只允许运行你的代码

如果(计数($_POST))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    相关资源
    最近更新 更多