我正在尝试使一个wordpress插件为客户生成一个唯一的订单id。我正在做如下,但它不是返回值。我的代码在下面。
class abc {
function __construct() {
add_action( 'publish_wpcf7s', array($this, 'send_mails_on_publish' ), 10, 2);
}
function setID() {
global $id;
$a = md5(time());
echo $id = substr($a,0,8);
}
function send_mails_on_publish($post)
{
global $post;
global $id;
$price = get_post_meta( $post->ID, 'quote_price', true );
$to = get_post_meta( $post->ID, 'email', true );
$subject ="Thank You! Please Pay $price Us For Order No. $id";
$message ="message";
$headers[] = "Disposition-Notification-To: $sender_email'n";
$headers[] = 'Content-Type: text/html; charset=UTF-8';
$headers[] = 'From: Example ' . "'r'n";
wp_mail( $to, $subject, $body, $headers );
}
}
定义$id
属性,初始化,然后在$this
的任何类方法中使用它
class abc {
private $id;
function setID() {
$a = md5(time());
$this->$id = substr($a,0,8);
}
function send_mails_on_publish($post) {
// use `$this->id` instead of `id`
}
}
如果你想让id
属性在每次创建类实例时自动生成,只需将其放在__construct()
方法中
function __construct() {
$this->setID();
}
你把setID()
叫到哪里去了?不管怎样,这段代码真的很臭。
检查:
class abc {
private $id = 0;
private $post;
function __construct() {
add_action('publish_wpcf7s', array($this, 'send_mails_on_publish'), 10, 2);
}
function getId() {
return $this->id;
}
function getPost() {
return $this->post;
}
function setId() {
$a = md5(time());
$this->id = substr($a, 0, 8);
}
function setPost($post) {
$this->post = $post;
}
function send_mails_on_publish() {
//do whatever you want.
$price = get_post_meta($this->post->ID, 'quote_price', true);
$to = get_post_meta($this->post->ID, 'email', true);
$subject = "Thank You! Please Pay $price Us For Order No. $this->id";
//.....
// do whatever you want
}
}
当你想使用它时:
$Abc = new abc();
$Abc->setId();
$Abc->setPost($post);
另一种方式,如果你传递$post
作为一个参数来构造你的对象,并设置$this->post
在那里。在这种情况下,你不需要setPost
方法,但你可以保留它,如果你想改变,但这不是一个好的设计。