我对OO还是比较陌生的,坦率地说,通常是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>当我尝试在句子结构中添加这个->arrayOfWords时,它说这是一个语法问题。
我想知道问题是否在于它在运行call_user_method,即使在输入句子之后,我还没有在表单中点击submit呢?我觉得它还没到那里吗?
添加:当我在浏览器中调用脚本时,在表单中单击submit之前,是当我看到警告消息时。
还添加了:也许我需要检查$arrayOfWords是否为null或sortHighestLetterRepeaterOfSentence中的什么东西?我尝试添加一个null检查,但它表示未定义的变量arrayOfWords,其中我测试它的!= null。我也在考虑isset,但目前还不清楚这是否能解决它。
发布于 2016-05-05 18:39:01
$arrayOfWords是一个只存在于__construct函数中的变量。
$this->arrayOfWords是一个私有类变量,它存在于该类的任何方法中,并且每个实例具有不同的值。
你为什么要用call_user_method?这个函数被废弃了(我认为PHP 7中删除了这个函数)。只是简单的说明,如果你在一个教程中看到了,你应该考虑一个新的教程,因为它将是过时的。
你可以这样做:
$sentenceCC->sortHighestLetterRepeaterOfSentence()如果必须使用,则可以使用call_user_func:
call_user_func([$sentenceCC, 'sortHighestLetterRepeaterOfSentence']);发布于 2016-05-05 18:42:30
是的,即使没有提交表单,此代码也将执行。
我认为您应该检查$_POST变量,只允许运行您的代码。
如果(计数( $_POST ))
https://stackoverflow.com/questions/37057862
复制相似问题