[英]Php Classes referencing instances
背景:我正在学习C#,工作表明我也选择了php,这就是这个问题的根源。
我提出了一个非常简单的例子来说明这一点。 在C#中,我可以引用一个类,在这种情况下, private Car car
创建该类的实例new Car();
然后继续使用其中包含的功能car.GasMilage();
。
Public abstract class vehicle
{
private Car car = new Car();
car.GasMilage();
}
Public class Car
{
private string color;
private int fuelCapacity;
private int milesDriven;
public double GasMilage()
{
double mpg = milesDriven/fuelCapacity;
return mpg;
}
}
我开始创建以下php类,该类最终在目录中循环并填充网站的选项卡以及每个选项卡中的项目数。 这个数字每周变化。 我想做的是在此类中重用函数,所以我想我的问题就变成了我需要将此类分解为每个具有单个函数的较小类,还是仅可以引用特定函数的某些输出? 我有几本书讨论了如何创建类,函数等,但是与C#示例类似,我找不到关于所有部分如何组合在一起的好信息。 谢谢。
<?php
/*Establishes an array containing all the names of the centers*/
class SiteDirectories
{
/*Defines an array with a variable named Sites*/
public $Sites = array();
/*Variable for keeping count of patients within directories*/
public $count=0;
/*A foreach loop that loops through the contents of directory Dir, each directory it finds it assigns a temp variable Site*/
function arrayBuilder()
{
/*Defines a variable Dir a directory path*/
$Dir = "Photos/*";
/*Loops through each directory within the Photos directory, uses Site to hold the temp variable*/
foreach (glob($Dir) as $Site)
{
/*Takes the basename of the current directory and calls it SiteName*/
$SiteName = basename($Site)." (".$this->ptCount($Site).")";
/*Adds the SiteName to the array list Sites*/
array_push($this->Sites, $SiteName);
$this->count = 0;
}
}
function ptCount($Site)
{
foreach(glob($Site."/*") as $dir)
{
$this->count = $this->count + 1;
}
return $this->count;
}
function tabCreator()
{
$ct = 1;
foreach($this->Sites as $tab)
{
echo "<li><a href='#tab$ct'>".$tab."</a></li>";
$ct = $ct + 1;
}
}
}
$SiteNames = new SiteDirectories;
$SiteNames->arrayBuilder();
echo $SiteNames->tabCreator();
?>
我的.php网站中引用了以下内容
<ul class='tabs'>
<?php
include 'SiteDirectories.php';
?>
</ul>
我不是要让别人提供“这是您应该输入的代码”,而是要讨论如何将OOP原理从C#链接到php,因为目前我无法建立连接。 谢谢。
我认为您不是真正的OOP,但是在这里,唯一要做的就是调用您创建的函数。 唯一要做的是将类定义下的三行迁移到模板文件。 背后的逻辑是只定义一次类,但每次需要时都使用它。
然后要引用PHP中的类,就像在C#中一样,但变量必须以$
开头。 如果要在PHP中使用C#定义的类,则必须在PHP中重写它,因为即使有可能将这样的C#代码链接到PHP上,这也太过分了...
我不是要请别人提供“这是您应该输入的代码”来生成有关将OOP原理从C#链接到php的讨论...
作为一个概念,OOP在所有语言中都非常相似。 语法不同。 我不是C#开发人员,但是您可以将C#的绝大多数OOP原理移植到PHP中。
...我是否需要将此类分解为较小的类,每个类都具有单个函数...
通常,只要您的类中的方法彼此紧密相关,并且该类旨在处理该工作就可以。
...或者我只能引用特定功能的某些输出?
您可以通过以下方式使用PHP类:
$siteDirectories = new SiteDirectories();
然后,您将像这样调用方法,并且能够“仅引用特定函数的某些输出”。
$siteDirectories->arrayBuilder();
注意 :我警告您不要在类中使用公共属性,而应选择访问器。 然后,这些属性将成为private $sites;
(或protected sites;
),然后将getSites()
方法添加到该类(与$count
相同)。
额外 : PHP:正确的方法对于新老PHP开发人员都是极好的参考。 我强烈建议您在开始使用PHP时对其进行复习。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.