【问题标题】:PHP Class variable access questionPHP 类变量访问问题
【发布时间】:2010-01-06 13:57:31
【问题描述】:

我在访问类变量时遇到问题。

我在课堂上有以下功能。

class Profile { 

    var $Heading;

    // ...

    function setPageTitle($title)
    {
        $this->Heading = $title;
        echo 'S: ' . $this->Heading;
    }

    function getPageTitle2()
    {       
        echo 'G: ' . $this->Heading;
        return $this->Heading;
    }

// ...
}

现在当我运行 $this->setPageTitle("test") 方法时,我只得到 ​​p>

G: S: test

getPageTitle2 函数有什么问题?顺便说一句,标题是公开的。请帮忙!

谢谢大家!

【问题讨论】:

  • 请提供调用方法的代码。
  • 整个代码位于 www.fearghal.com/Untitled-1.phps 函数名称是 SetContent() 和 getPageContents() ...他们调用的函数是问题。

标签: php class


【解决方案1】:

现在当我运行 $this->setPageTitle("test") 方法时,我只得到

G: S: test

这听起来难以置信。你确定你没有在跑步吗:

$this->getPageTitle2();
$this->setPageTitle("test");

PHP - 与大多数编程语言一样 - 是一种命令式语言。这意味着你做事的顺序很重要。在您调用getPageTitle2 时未设置变量$this->Header

【讨论】:

  • 好吧,我还有其他函数 //(唯一调用 set 函数的函数) function getPageContents() { $this->setPageTitle("test"); } 和另一个函数 setContent // 运行 getPageTitle2 { echo '
    '.$this->getPageTitle2().'
    ';所以我认为在一个类中放置函数并不重要。也许 getPageContents() 必须放在 Set() 之上?
  • @Fergs 类中方法的放置无所谓,这个我可以保证。在您的代码中的某处,您在调用 setPageTitle() 之前显式调用 getPageTitle2() - 没有隐式或其他自动方式来调用名为 getPageTitle2 的方法。
  • 这就是我的想法:我已将代码上传到 www.fearghal.com/Untitled-1.phps 它半大,但 SetContent 和 getPageContents 在那里并调用有问题的函数.. .你能看看吗?
  • @fergs 该代码只是一个类。它根本不会做任何事情。您的问题可能在于使用该类的代码。
【解决方案2】:

如果你有“G:S:test” 这意味着您在 setPageTitle 之前调用了 getPageTitle2 ! 然后看起来很正常:我建议先设置然后获取。

【讨论】:

    【解决方案3】:

    你必须在函数中声明标题和标题......我不知道你是否已经这样做了

    查看函数调用顺序

    【讨论】:

    • 是的,我的课开始像:class Profile { var $Heading;但是即使 $title 直接输入到函数中,它是否也需要这样做?
    【解决方案4】:
    class Profile { 
    
    var $Heading;
    
    // ...
    
    function setPageTitle($title)
    {
        $this->Heading = $title;
        echo 'S: ' . $this->Heading;
    }
    
    function getPageTitle2()
    {       
        echo 'G: ' . $this->Heading;
        return $this->Heading;
    }
    
    // ...
    }
    

    我猜你正在做这样的事情:

    $profile = new Profile();
    $profile->setPageTitle("test");
    $profile->getPageTitle2();
    

    这将导致以下输出:

    S: testG: test
    

    如果你 echo $profile 你会得到 ​​p>

    test
    

    那么您认为问题是什么,或者您没有完成您想要完成的事情?

    我也可能将$Heading 声明为

    private $heading;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-12
      • 2011-09-21
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多