[英]Extending one class inside other class in php
我有一个A类,它扩展了B类如下
Class A extends B
{
function SendMAil(){
/* Here Send Mail Code is wriiten */
}
}
我有另一个C类,我已经实现了多线程概念,我需要从中获取C frrom Thread
Class C extends Thread {
function SendMail2(){
/* Code For SendMail2() */
}
}
现在我需要在A类中扩展Thread Class,这样我就可以在A类中使用多线程的功能,我该怎么做呢
PS:当我们为PHP安装pthread库时,类Thread是php中的内置类,因此我们不能在Thread类中进行任何更改。
我卡在那里!! 我怎样才能做到这一点??
提前致谢 !!
那你应该使用特征。 特质很像类,但它们很可能只是用来捆绑你需要很多并且彼此之间有关系的东西。
例如:
trait ThreadTrait {
public function doSomeMultithreading() {
// Put your multithreading code in here
}
}
Class A extends B {
use ThreadTrait;
public function aFunctionWhereYouCanUseMultithreadingNow() {
echo 'Multithreading possible in every class now!:)';
}
}
现在,您可以在所需的每个类中访问多线程所需的所有函数。
您是否可以extends类B
带班Thread
先然后扩展的类A
带班B
。 您将在B
类中获得Thread
类的所有公共和受保护成员。 像这样:
<?php
class Thread {
public function threadfunc() {
echo "This is thread class";
}
}
class B extends Thread {
public function bfunc()
{
$this->threadfunc();
}
}
Class A extends B {
function SendMAil(){
echo "sendmail";
}
}
Class C extends Thread {
function SendMail2(){
echo "send mail 2";
}
}
$obj = new A();
$obj->bfunc();
特征在这里没有用,因为除了其他特征之外,它们不能由任何东西组成; 特征不能extend
类,但只能use
其他特征。
无论pthreads如何,你描述的继承都很奇怪。
关于pthreads, Threaded
对象具有与普通PHP对象不同的语义,普通的PHP对象没有为线程做好充分准备,这是你需要在pthreads
使用它们从而在多pthreads
时非常好的理由。 - 线程代码。
所以,一个例子; 因为A,B和C有点抽象;)
如果我们想象您的后端应用程序负责注册新用户; 更新数据库和发送电子邮件,创建他们的小猫头像(显然),并做一些其他繁重的工作。
我们将做出以下假设:
Pool
,因为这是一个很好的做法, Threaded
) 有线程的代码
class Mailer extends Threaded {
public function __construct($email, $subject, $message) {
$this->email = $email;
$this->subject = $subject;
$this->message = $message;
}
public function send() {
if (!mail($this->email, $this->subject, $this->message)) {
throw new \RuntimeException(
"the mailman is a failure ...");
}
}
public function run() {
/* when I am submitted to a
Pool or Worker, I will send the email */
$this->send();
/* alternatively, Mailer could be a Thread
but I won't encourage you to be wasteful ;) */
}
protected $email;
protected $subject;
protected $message;
}
没有线程的应用程序代码
class Something {
public function thing() {
}
}
使用任意和线程代码的代码
class Register {
public function __construct(Pool $pool, Mailer $mail, Something $some) {
$this->pool = $pool;
$this->mail = $mail;
$this->some = $some;
}
public function doRegistration() {
/* ... do registration things ... */
$this->some->thing();
/* send the email in the background */
$this->pool
->submit($this->mail);
/* do the next thing */
$this->some->thing();
}
protected $pool;
protected $mail;
protected $other;
}
/* somewhere else in the application */
$pool = new Pool(2);
$some = new Something();
/* here */
$mail = new Mailer("krakjoe@php.net", "oi", "look here");
$register = new Register($pool, $mail, $some);
$register->doRegistration();
/* somewhere else suitable in the application */
$pool->shutdown();
注意:没有必要在后台线程中发送电子邮件,这只是示例代码
进一步阅读:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.