PHP $这个时候从没有在课堂内外设置为公共变量对象上下文 [英] PHP $this when not in object context for set public variable from out of class
本文介绍了PHP $这个时候从没有在课堂内外设置为公共变量对象上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有简单的类,我想从淘汰类的设置公共
变量。
< PHP类AlachiqHelpers
{
公共$高度; 公共静态功能的getHeight($高度)
{
返回$这个 - >高度 - 50;
} 公共静态函数调用setHeight($高度)
{
$这个 - >高度= $高度;
}
}
在结果我得到这个错误:
这个时候不是在对象上下文使用$
块引用>解决方案的
$这种
关键字不能在静态上下文中使用!案例1:
您需要删除
静态
从功能确定指标关键字。而不是
的公共静态函数调用setHeight($高度){
应
公共函数调用setHeight($高度){
案例2:
如果你真的需要,使其(功能)为
静态
...你可以只用自
关键字来访问该变量。公共静态$高度;
公共静态函数调用setHeight($高度)
{
自:: $高度= 22;
}请记住,
$高度
变量也是由静态
工作code ..(静态的)
< PHP
类AlachiqHelpers
{
公共静态$高度;
公共职能的getHeight()
{
返回self :: $高度 - 50;
} 公共静态函数调用setHeight($ height1)
{
自:: $高度= $ height1;
}
}$ A =新AlachiqHelpers();
$ A->自动调用setHeight(180);
回声$ A->的getHeight();
输出:
130
I have simple class and I want to set
public
variable from out of class.<?php class AlachiqHelpers { public $height; public static function getHeight($height) { return $this->height - 50; } public static function setHeight($height) { $this->height = $height; } }
In Result i get this error:
Using $this when not in object context
解决方案The
$this
keyword cannot be used under static context !.Case 1:
You need to remove the
static
keyword from the function defintion.Instead of
public static function setHeight( $height ){
Should be
public function setHeight( $height ){
Case 2:
If you really need to make it(function) as
static
... You could just use theself
keyword to access the variable..public static $height; public static function setHeight( $height ) { self::$height=22; }
Keep in mind that the
$height
variable is also madestatic
The working code.. (static one)
<?php class AlachiqHelpers { public static $height; public function getHeight() { return self::$height - 50; } public static function setHeight($height1) { self::$height = $height1; } } $a = new AlachiqHelpers(); $a->setHeight(180); echo $a->getHeight();
OUTPUT :
130
这篇关于PHP $这个时候从没有在课堂内外设置为公共变量对象上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文