gpt4 book ai didi

php - 在 PHP 中,你如何创建可重用对象?对此有最佳实践吗?你喜欢哪个?

转载 作者:可可西里 更新时间:2023-11-01 12:44:39 25 4
gpt4 key购买 nike

我正在用 php 创建一些可重复使用的对象,我想知道构建它们的最佳方法是什么。下面我有 2 个不同方法的例子。

Class Uploader{
public $Filename;
public $Directory;

function upload(){
upload_file($this->Filename, $this->Directory)
}
}

// Then use the class above like this.
$u = new Uploader;
$u->Filename = 'foo.png'; // Set all the props
$u->Directory = 'bar/' // ^ ^ ^ ^
$u->upload(); // Then Execute

或者这样做会更好吗...

Class Uploader {
function uploader($filename, $directory){
upload_file($filename, $directory)
}
}

// Then use the class above like this.
$u = new Uploader;
$u->uploader('foo.png', 'bar/') // Obviously much less code, All in One.

在这两种方法中,哪一种是首选,它们是速度差异还是使用一种方法比另一种方法有任何好处?
我赞成示例 #1,但他们是对此的最佳实践吗?

最佳答案

为什么不能两者兼顾?

class Uploader
{
public
$filename,
$directory;

public function __construct( $name = '', $dir = '', $autoUpload = false )
{
$this->filename = $name;
$this->directory = $dir;
if ( $autoUpload )
{
$this->upload()
}
}

public function upload()
{
//check your values
...code...
upload_file( $this->filename, $this->directory );
}
}

使用这种技术,您可以简单地自动上传文件:

$uploader = new Uploader( $name, $dir, true);

或者您可以手动构建对象:

$uploader = new Uploader();
$uploader->filename = $name;
$uploader->directory = $dir;
$uploader->upload();

关于php - 在 PHP 中,你如何创建可重用对象?对此有最佳实践吗?你喜欢哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7272521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com