【发布时间】: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->sortHighestLetterRepeaterOfSentence()?是的,$this是必需的。