首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >值丢失或丢失

值丢失或丢失
EN

Stack Overflow用户
提问于 2016-05-05 18:36:34
回答 2查看 80关注 0票数 1

我对OO还是比较陌生的,坦率地说,通常是PHP。我有一个类,我在构造函数中分配数组值。但是,当我稍后访问数组时,它告诉我数组是空的。你知道这怎么会超出范围吗?

代码语言:javascript
复制
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
    }
...
}

这可从以下网址获得:

代码语言:javascript
复制
<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,但目前还不清楚这是否能解决它。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-05-05 18:39:01

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

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

你为什么要用call_user_method?这个函数被废弃了(我认为PHP 7中删除了这个函数)。只是简单的说明,如果你在一个教程中看到了,你应该考虑一个新的教程,因为它将是过时的。

你可以这样做:

代码语言:javascript
复制
$sentenceCC->sortHighestLetterRepeaterOfSentence()

如果必须使用,则可以使用call_user_func

代码语言:javascript
复制
call_user_func([$sentenceCC, 'sortHighestLetterRepeaterOfSentence']);
票数 3
EN

Stack Overflow用户

发布于 2016-05-05 18:42:30

是的,即使没有提交表单,此代码也将执行。

我认为您应该检查$_POST变量,只允许运行您的代码。

如果(计数( $_POST ))

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37057862

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档