Jump to content

Recommended Posts

Posted

The Basics of OOP in PHP

 

The language used for runescape private servers is Java, Java is scripted in OOP. When you look at OOP in PHP you'll probably see alot of similarity.

 

The Class

First you need to create a class.

(Note The name must start with a capital letter)

class MyFirstPage() {
 //Your methods here
}

 

In OOP PHP you have a constructor. The constructor is run immediately after the class is called. The custructor looks like this:

public function __construct() {
 //What you want to run first
}

 

Like in Java you need to declare a variable before you can write to it or use it. Do that like this:

public $var;

 

Lets put it all to work!

class MyFirstPage {
  protected $_name;
  protected $_age;
  
  public function __construct($name, $age) {
     $this->_name = $name;
     $this->_age = $age;
  }

  public function getName() {
     return $this->_name;
  }

  public function getAge() {
     return $this->_age;
  }
}

Now save that as MyFirstPage.php (Usually a class file is named after the class).

 

Now lets make the page to let it show!

include './MyFirstPage.php';

$myfirstpage = new MyFirstPage('Michael', '15'); //Change these values to make it use another name or age

echo 'The name is: '. $myfirstpage->getName() .' and im: '. $myfirstpage->getAge() .' years old';

 

and save that as index.php

 

Now upload index.php and MyFirstPage.php to your webhost and test it out!

 

NOTE: You dont need to end the PHP file with ?> when the whole file is only PHP without HTML.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...