调用和更新php对象变量(定义变量时出现问题)

调用和更新php对象变量(定义变量时出现问题),php,oop,Php,Oop,我在用PHP创建类时遇到了一个问题。当我定义两个变量时。PHP会自动更新两个变量,使其相同。为什么会这样?我想要的输出如下: <?php class testClass { public $public_str; public $public_int; function __construct() { $this->$public_str = "this is a string "; $this->$public_int = 0; } //string

我在用PHP创建类时遇到了一个问题。当我定义两个变量时。PHP会自动更新两个变量,使其相同。为什么会这样?我想要的输出如下:

<?php

class testClass {

public $public_str;
public $public_int;

function __construct() {
    $this->$public_str = "this is a string ";
    $this->$public_int = 0;
}

//string
function newVar($newText) {
  $this->$public_str = $newText;
}

function getPublicVar() {
  return $this->$public_str;
}

//var
function newInt($newInt){
  $this->$public_int = $newInt;
}

function getPublicInt(){
  return $this->$public_int;
}

}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
<title>Test</title>
</head>
<body>

<?php


$object_test = new testClass;
$object_test->newVar("this is the new string ");
$object_test->newInt(10);


$output = '<p> hello World:  ' ;
$output .= $object_test->getPublicVar();
$output .= $object_test->getPublicInt();
$output .= '</p>';

//alternatively
$output .= '<p> hello World:  ' ;
$output .= $object_test->$public_str;
$output .= $object_test->$public_int;
$output .= '</p>';

echo $output;

?>


</body>
</html>
你好,世界:这是一个新的字符串10

但我得到:

你好,世界:1010

我的代码有什么问题。定义了变量,然后我使用construct函数初始化变量。在我的代码中,当我更新变量时,两个变量同时更新。最后一个命令不应该出现这种情况

我在一个名为index.php的自发布网页中创建了它,用于测试目的,并解释代码中发生了什么。您必须运行具有php功能的服务器才能看到我的示例。代码如下:

<?php

class testClass {

public $public_str;
public $public_int;

function __construct() {
    $this->$public_str = "this is a string ";
    $this->$public_int = 0;
}

//string
function newVar($newText) {
  $this->$public_str = $newText;
}

function getPublicVar() {
  return $this->$public_str;
}

//var
function newInt($newInt){
  $this->$public_int = $newInt;
}

function getPublicInt(){
  return $this->$public_int;
}

}

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
<title>Test</title>
</head>
<body>

<?php


$object_test = new testClass;
$object_test->newVar("this is the new string ");
$object_test->newInt(10);


$output = '<p> hello World:  ' ;
$output .= $object_test->getPublicVar();
$output .= $object_test->getPublicInt();
$output .= '</p>';

//alternatively
$output .= '<p> hello World:  ' ;
$output .= $object_test->$public_str;
$output .= $object_test->$public_int;
$output .= '</p>';

echo $output;

?>


</body>
</html>

试验
您的语法错误

$this->$public_str = $newText;
应该是:

$this->public_str = $newText;

其他变量也是如此。

在访问类的属性时,不应在前面使用变量标识符
$
。响应速度非常快。这就解决了我的问题。!谢谢。只是一些关于使用类的东西-属性通常不应该是公共的,特别是当你有方法访问它们的时候。