Jump to content

Defining classes PHP (newbe problem)

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
nick3

nick3

    Newbie

  • Members
  • PipPip
  • 29 posts
Hello, I have just started to program some in PHP, I would like to get a word from the user and make a object (class word) out of it and put it in an array that is in an other object (class wordcollection).

<html>

    <head>

        <title>A program</title>

    </head>

    <body>

        <div style="width: 500px; margin-left: 0;">

        	<form action="index.php" method="POST">

        	Enter a sentence:<br>

        	<input type="text" name="word" size="30"><br>

        	<input type="submit" value="Send">

        	</form>

        </div>

        <?php

        //CODE

        ?>

    </body>

</html>

In the PHP-tag I would like to initilize a new wordcollection, and I would like to create a new instance of the class word from what I get from POST everytime the "Send" button is clicked,and the word added to the array in wordcollection and then to print all the words in the array on the screen...

I tryed something like this, but it does not work at all!


<?php         

        include('classes.php');

        

        if($wordcollection == null)

        $wordcollection = new WordCollection();


        $userword = $_POST['word'];

        

        $tmpword = new Word($sentence);

        $wordcollection->add_word($tmpword);

        foreach ($wordcollection->wordArray->get_word() as $value) {

            echo $value;


?>

Here is my class code...

class Word {

  public $word;


  public function __construct($word){

      $this->word = $word;

  }


  public function get_word(){

      return $this->word;

  }

}


class WordCollection{

  public $wordArray;


  public function __construct(){

      $this->wordArray = array();

  }

  public function add_word($word){

      $this->wordArray = array_push($this->wordArray, $word);

  }

  public function print_array(){

      return $this->wordArray;

  }


 }

Thanks a lot for any help!

#2
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
Currently, each time you press submit, a new WordCollection object is created and a new Word is added to the collection. If you only wish to create a single WordCollection object, and continually add Word objects to the collection after each submission, you need to use the singleton design pattern.