php oop, updating textfile


So i haven’t been doing any php coding lately, and i figured i should do some again. My plan is to integrate a website with my minecraft server, so i can update the whitelist and banning list form the site. so atm i have some poblems with my (terrible) oop code:

if i run this with:

$mc=new Minecraft;

echo $mc->updateWhitelist(‘add’,3);[/php]

it adds the username no matter what -_-

can someone help me? :slight_smile:

Best regards
Anders Fylling

Your bug is simple and is due to the way strpos does the comparison. It checks the type explicitely, which leads to your string never being matched.

A simple change to fix it, at line 19, is as follows:
[php]if(strpos($filenr, (string)$u)===false){[/php]

The (string) typecasting operator allows you to convert the integer that you are passing into a string, which strpos can cope with in a better fashion.

Additionally, can I recommend a bit of OOP structure to this? You’re missing all the good points of OO by throwing everything into one class. It’s as though you did not actually have a class at all. I have reformatted your code a bit here: .

What I have done might seem backward to start with, but as you’ve noted, you’ll have more than one file parser - one for a banlist, one for a blacklist, one for this whitelist. I have implemented all the file-reading functions in an abstract class, which needs to be extended to function.
The extension requires the presence of two functions:

  • parseLine converts a line of your file to an object
  • objectToLine converts an object to a line in your file

This allows you to set arbitrary reading and writing formats for your file in addition to extending the class with methods of your choosing. The file data is cached in $this->cache, which allows you to not have to worry too much about lots of file read/write operations.

The main advantage of this is simple: you will have one parser logic for a minimum of three files. If you want to make a change to all three of them - it is perfectly possible and trivial. This is the main benefit of OOP: code maintenance.

Sponsor our Newsletter | Privacy Policy | Terms of Service