简体   繁体   English

OOP PHP和实例化类

[英]OOP PHP and instantiating classes

I am relatively new to OOP approach to PHP, but just wanted something clarified: 对于PHP的OOP方法,我比较陌生,但只想澄清一些内容:

if(isset($_POST['insertProduct']) && !empty($_POST['productName'])){
    $newProduct = new product();
    $newProduct->productName = $_POST['productName'];
    $newProduct->servingSize = $_POST['servingSize'];
    $productID = $newProduct->insertProduct();   
}

So the above code is executed when a form is posted to the page to enter a new product into the DB. 因此,当将表单发布到页面以将新产品输入数据库时​​,将执行上述代码。

$selectProduct = new product();
if($selectProduct->getProducts()){
    foreach($selectProduct->getProducts() as $product){ 
        echo '<option value="' .
            $product['productID'] . '">' . 
            $product['productName'] . '</option>';
    }
}

The above piece is on the same page, and obviously now there are two instances of the product class that exist (assuming the form has been posted to add a new product). 上面的内容在同一页上,显然现在存在两个产品类实例(假设已过帐表单以添加新产品)。 Does this show a benefit of the OO approach? 这是否显示了面向对象方法的好处? As in using two instances to access different methods? 如在使用两个实例来访问不同的方法? Or is it a bad way of doing what I want to do? 还是做我想做的事的不好方法?

I think getProducts should be at least a static method, since it doesn't have nothing to do with the instance of a product. 我认为getProducts应该至少是静态方法,因为它与产品实例无关。 A product class should represent only the single data of a product, therefore generic non-instances methods should be set to static or moved to another class. 产品类应仅表示产品的单个数据,因此,通用非实例方法应设置为静态或移至另一个类。

I'd suggest you to create a Factory class that will create the product instances for you: 我建议您创建一个Factory类,该类将为您创建product实例:

$array = FactoryProducts::getProducts();

But you surely need to move that method outside the product class. 但是您肯定需要将该方法移至product类之外。 For the rest, everything seems fine. 其余的一切似乎都很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM