Jump to content

Splitting a class over multiple files


chronister

Recommended Posts

Hello All,

 

I am taking a serious leap into OOP and am attempting to create a form class to make forms easier to deal with. I am trying to spread a class over multiple files.

 

Basically I want to do something like this...

 

main.class.file.php

<?php
class myClass{
  var $myVar;
  var $messages;

  function myClass(){
      $this->myVar = 1;
       include('path/to/file'); // contains methods I wish to be available in this class
  }

  function someMethod()
  {
     $this->addMessage('1','hello world'); // addMessage is defined in the included file
      echo $this->messages;
  }

}
?>

 

included file

<?php
class errorMessage extends myClass{
function addMessage($key,$message)
{
    $messages[$key] = $message;
    $this->messages = $messages;
    return $this->messages;
}
}
?>

 

I hope this makes sense, I am trying to create 1 class split into different files for easier code management, but have all methods and objects available anywhere after the include statement.

 

Is this possible, or am I going about it in the wrong way??

 

Thanks,

 

nate

Link to comment
https://forums.phpfreaks.com/topic/135098-splitting-a-class-over-multiple-files/
Share on other sites

Its doesn't exactly work that way. Firstly, from an OOP perspective errorMessage isn't really at all related to myClass so it defintaely shouldn't extend it.

 

You would be better to have errorMessage as a completely seperate entity IMO.

 

errorMessage.class.php

<?php

class errorMessage {

  private $messages;

  public function __construct() {
    $this->messgaes = array();
  }

  public function addMessage($message) {
    $this->messages[] = $message;
  }

  public function getMessages() {
    return $this->messages;
  }

}
?>

 

<?php

include 'errorMessage.class.php';

class myClass {
  
  private $myVar;
  private $messages;

  public function __construct() {
    $this->myVar = 1;
    $this->messages = new errorMessage;
  }

  function someMethod() {
    $this->messages->addMessage('hello world');
    echo implode('<br />', $this->messages->getMessages());
  }

}
?>

Ahhhh... Thank you thorpe. I kinda thought that I was going about it in the wrong way.

 

This is the first big complete class I have tried writing. I have messed with modifying other classes, but not created one on my own.

 

Thanks for this line, I did not realize I could access the object like this.

 

$this->messages->addMessage();

 

Thanks, that will get me well on my way with this.

 

Nate

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.