关于__constructors和passing:它们的作用是什么?关于父母:他们是否接受兄弟姐妹的对象,反之亦然


About __constructors and passing: what are they for? About parents: do they take the objects of siblings and vice versa?

好的,所以书中说:"当创建一个新对象时,你可以向被调用的类传递一系列参数。这些参数被传递给类中一个特殊的方法,称为构造函数,它初始化各种属性。

我真的不知道"传球"是什么,尤其是在这种情况下。我还读到,如果使用构造函数方法,它将使用类的名称。所以,如果你有


class User
{
  function __constructor($param1, $param2)
  {
    echo "User construct."
  }
}
user();

应该发生什么?我说不出来,因为我的巴氏杆菌说这是"可能的CRF发作",不管这意味着什么。。。。

接下来,我们将看到本书后面的部分,代码中写道:


$bothCatsObject = new tiger();
echo "Tigers have...
"; echo "Fur: " . $bothCatObject->fur . "
"; echo "Stripes: " . $bothCatObject->stripes; class cat { public $fur; // Cats have fur. function __construct() { $this->fur = "TRUE"; } } class tiger extends Cats { public $stripes; // Tigers have stripes. function __construct() { parent::__construct(); // Call parent construct first. $this->stripes = "True"; } }

这第二块代码的目的是表明当调用一个对象时,它的构造会激活并设置活动内存中的属性吗?或者,也可以说,当调用一个属性时,如果该属性的值是在构造函数中设置的,那么它就会有一个值。如果它的值没有在构造函数中设置(例如,如果它在非构造函数方法中设置),则会返回错误?

书中说"这段代码以典型的方式利用了构造函数继承的好处"。所以,我希望我不会太远。我想知道为什么构造函数很有用。如果我在研究的这一点上需要知道,那么在哪些应用程序中构造函数是必要的?

最后,在这种情况下,"cats"类永远不会被分配对象。因为"tiger"扩展了cats类,所以cats类可以通过tiger对象调用吗?下面是我的意思的一个例子:


$bothCatsObject = new tiger();
$bothCatsObject->catTest();  //Does this return an error?
class cat
{
  public $fur; // Cats have fur.
  function __construct()
  {
    $this->fur = "TRUE";
  }
  function catTest()
  {
    echo "The object works for cats and tigers."
  }
}
class tiger extends Cats
{
  public $stripes; // Tigers have stripes.
  function __construct()
  {
    parent::__construct();  // Call parent construct first.
    $this->stripes = "True";
  }
  function tigerTest()
  {
    echo "The object works for tigers and cats."
  }
}

同样,我可以从一个新的cat对象调用"tiger"类中内置的函数吗?因为tiger类是cat类的兄弟?换句话说,用这个代码替换前一个代码块的第1行和第2行是否有效,或者它会返回一个错误:

$bothCatsObject = new cat();
$bothCatsObject->tigerTest();  //Does this return an error?

首先,在本地机器中运行脚本。

好:

class User
{
  function __constructor($param1, $param2)
  {
    echo "My Name is {$param1} {$param2} ;)";
  }
}

初始化用户类时,它将自动运行__construct函数:

$user = new User("John","Smith");
// this will output "My Name is John Smith ;)"

构造函数在创建类的新实例时随时运行。一个例子是:假设你想启动数据库连接并做一些繁重的工作,你可以写一个构造函数来检查是否已经有数据库连接,如果没有创建它,并处理设置所有默认配置

$database = new Database();
// will automatically create a connection
// ex: mysql_connect("username","password","....
//     mysql_select_db(...
// and so on