I tried creating an object in PHP for PHPMailer to be used in development enviroments.
class Configuration
function __construct()
{
// creating an object for configuration, setting the configuration options and then returning it.
return $config = (object) array(
'DevEnv' => true, // DevEnv setting is used to define if PHPMailer should use a dev mail address to send to or not.
'ReceiverEmail' => 'email@gmail.com', // Set the develop enviroment email.
'ReceiverName' => 'name' // Set the develop enviroment email name.
);
}
}
Then I call the class in another controller:
protected $configuration;
function __construct()
{
$this->configuration = new Configuration();
}
function SendInfoMail()
{
foreach($this->configuration as $config) {
var_dump($config);
if ($config->DevEnv == true) {
// do stuff
}else{
// do stuff
}
}
for some reason, it just dumps an empty object. I also tried using
var_dump($config->ReceiverEmail);
Constructors do not work that way. They do not have a return value – http://php.net/manual/en/language.oop5.decon.php
new ClassA
always returns an instance of that class.
You are using constructor incorrectly. See this working example:
class Configuration {
protected $configuration;
function __construct() {
// creating an object for configuration, setting the configuration options and then returning it.
$this->configuration = (object) array(
'DevEnv' => true, // DevEnv setting is used to define if PHPMailer should use a dev mail address to send to or not.
'ReceiverEmail' => 'email@gmail.com', // Set the develop enviroment email.
'ReceiverName' => 'name' // Set the develop enviroment email name.
);
}
}
class Class2 {
//protected $configuration;
function __construct() {
$this->configuration = new Configuration();
}
function SendInfoMail() {
var_dump($this->configuration);
foreach($this->configuration as $config) {
if ($config->DevEnv == true) {
// do stuff
}else{
// do stuff
}
}
}
}
$t = new Class2();
$t->SendInfoMail();
You have instance of Configuration class. Instead of that, try to add new method let's say "getProperties()".
class Configuration
function getProperties()
{
// creating an object for configuration, setting the configuration options and then returning it.
return $config = (object) array(
'DevEnv' => true, // DevEnv setting is used to define if PHPMailer should use a dev mail address to send to or not.
'ReceiverEmail' => 'email@gmail.com', // Set the develop enviroment email.
'ReceiverName' => 'name' // Set the develop enviroment email name.
);
}
}
So you can call it wherever you want:
protected $configuration;
function __construct()
{
$this->configuration = new Configuration();
}
function SendInfoMail()
{
foreach($this->configuration->getProperties() as $config) {
var_dump($config);
if ($config->DevEnv == true) {
// do stuff
}else{
// do stuff
}
}