Search Results

Search found 1449 results on 58 pages for 'oop'.

Page 26/58 | < Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >

  • Constructor Overloading

    - by Mark Baker
    Normally when I want to create a class constructor that accepts different types of parameters, I'll use a kludgy overloading principle of not defining any args in the constructor definition: e.g. for an ECEF coordinate class constructor, I want it to accept either $x, $y and $z arguments, or to accept a single array argument containg x, y and z values, or to accept a single LatLong object I'd create a constructor looking something like: function __construct() { // Identify if any arguments have been passed to the constructor if (func_num_args() > 0) { $args = func_get_args(); // Identify the overload constructor required, based on the datatype of the first argument $argType = gettype($args[0]); switch($argType) { case 'array' : // Array of Cartesian co-ordinate values $overloadConstructor = 'setCoordinatesFromArray'; break; case 'object' : // A LatLong object that needs converting to Cartesian co-ordinate values $overloadConstructor = 'setCoordinatesFromLatLong'; break; default : // Individual Cartesian co-ordinate values $overloadConstructor = 'setCoordinatesFromXYZ'; break; } // Call the appropriate overload constructor call_user_func_array(array($this,$overloadConstructor),$args); } } // function __construct() I'm looking at an alternative: to provide a straight constructor with $x, $y and $z as defined arguments, and to provide static methods of createECEFfromArray() and createECEFfromLatLong() that handle all the necessary extraction of x, y and z; then create a new ECEF object using the standard constructor, and return that Which option is cleaner from an OO purists perspective?

    Read the article

  • Using pointers to adjust global objects in objective-c

    - by Rob
    Ok, so I am working with two sets of data that are extremely similar, and at the same time, these data sets are both global NSMutableArrays within the object. data_set_one = [[NSMutableArray alloc] init]; data_set_two = [[NSMutableArray alloc] init]; Two new NSMutableArrays are loaded, which need to be added to the old, existing data. These Arrays are also global. xml_dataset_one = [[NSMutableArray alloc] init]; xml_dataset_two = [[NSMutableArray alloc] init]; To reduce code duplication (and because these data sets are so similar) I wrote a void method within the class to handle the data combination process for both Arrays: -(void)constructData:(NSMutableArray *)data fromDownloadArray:(NSMutableArray *)down withMatchSelector:(NSString *)sel_str Now, I have a decent understanding of object oriented programming, so I was thinking that if I were to invoke the method with the global Arrays in the data like so... [self constructData:data_set_one fromDownloadArray:xml_dataset_one withMatchSelector:@"id"]; Then the global NSMutableArrays (data_set_one) would reflect the changes that happen to "array" within the method. Sadly, this is not the case, data_set_one doesn't reflect the changes (ex: new objects within the Array) outside of the method. Here is a code snippet of the problem // data_set_one is empty // xml_dataset_one has a few objects [constructData:(NSMutableArray *)data_set_one fromDownloadArray:(NSMutableArray *)xml_dataset_one withMatchSelector:(NSString *)@"id"]; // data_set_one should now be xml_dataset_one, but when echoed to screen, it appears to remain empty And here is the gist of the code for the method, any help is appreciated. -(void)constructData:(NSMutableArray *)data fromDownloadArray:(NSMutableArray *)down withMatchSelector:(NSString *)sel_str { if ([data count] == 0) { data = down; // set data equal to downloaded data } else if ([down count] == 0) { // download yields no results, do nothing } else { // combine the two arrays here } } This project is not ARC enabled. Thanks for the help guys! Rob

    Read the article

  • PHP Session Class and $_SESSION Array

    - by Gianluca Bargelli
    Hello, i've implemented this custom PHP Session Class for storing sessions into a MySQL database: class Session { private $_session; public $maxTime; private $database; public function __construct(mysqli $database) { $this->database=$database; $this->maxTime['access'] = time(); $this->maxTime['gc'] = get_cfg_var('session.gc_maxlifetime'); session_set_save_handler(array($this,'_open'), array($this,'_close'), array($this,'_read'), array($this,'_write'), array($this,'_destroy'), array($this,'_clean') ); register_shutdown_function('session_write_close'); session_start();//SESSION START } public function _open() { return true; } public function _close() { $this->_clean($this->maxTime['gc']); } public function _read($id) { $getData= $this->database->prepare("SELECT data FROM Sessions AS Session WHERE Session.id = ?"); $getData->bind_param('s',$id); $getData->execute(); $allData= $getData->fetch(); $totalData = count($allData); $hasData=(bool) $totalData >=1; return $hasData ? $allData['data'] : ''; } public function _write($id, $data) { $getData = $this->database->prepare("REPLACE INTO Sessions VALUES (?, ?, ?)"); $getData->bind_param('sss', $id, $this->maxTime['access'], $data); return $getData->execute(); } public function _destroy($id) { $getData=$this->database->prepare("DELETE FROM Sessions WHERE id = ?"); $getData->bind_param('S', $id); return $getData->execute(); } public function _clean($max) { $old=($this->maxTime['access'] - $max); $getData = $this->database->prepare("DELETE FROM Sessions WHERE access < ?"); $getData->bind_param('s', $old); return $getData->execute(); } } It works well but i don't really know how to properly access the $_SESSION array: For example: $db=new DBClass();//This is a custom database class $session=new Session($db->getConnection()); if (isset($_SESSION['user'])) { echo($_SESSION['user']);//THIS IS NEVER EXECUTED! } else { $_SESSION['user']="test"; Echo("Session created!"); } At every page refresh it seems that $_SESSION['user'] is somehow "resetted", what methods can i apply to prevent such behaviour?

    Read the article

  • Zend_Form and Liskov Substitution Principle

    - by blockhead
    A very common pattern I see (I'm picking on Zend Framework, only because I was dealing with it at the moment of this question), is something like this: class My_Form extends Zend_Form { public function init() { $this->addElement(); } } Zend_Form is not an abstract class, but is perfectly usable on its own. This seems to be "recommended" as place to "encapsulate" your forms into a nice class. Does this violate the Liskov Substitution Principle? Each subclass of Zend_Form will have a wildy different behavior than the base class. Would it be better to use composition for this, or am I totally misunderstanding this principle?

    Read the article

  • Why is there no parameter contra-variance for overriding?

    - by Oak
    C++ and Java support return-type covariance when overriding methods. Neither, however, support contra-variance in parameter types - instead, it translates to overloading (Java) or hiding (C++). Why is that? It seems to me that there is no harm in allowing that. I can find one reason for it in Java - since it has the "choose-the-most-specific-version" mechanism for overloading anyway - but can't think of any reason for C++. Example (Java): class A { public void f(String s) {...} } class B extends A { public void f(Object o) {...} // Why doesn't this override A.f? }

    Read the article

  • Abstract attributes in Python

    - by deamon
    What is the shortest / most elegant way to implement the following Scala code with an abstract attribute in Python? abstract class Controller { val path: String } A subclass of Controller is enforced to define "path" by the Scala compiler. A subclass would look like this: class MyController extends Controller { override val path = "/home" }

    Read the article

  • mysqli and php requesting rows returned in object oriented scripting...

    - by Matt
    in object oriented php mysqli I am trying to request a username, and return if it matches a row, without actually returning any user data. How would I write this?...so far I have... $sql = "SELECT NULL FROM database WHERE usernick=?"; $stmt = $link->prepare($sql) $stmt->bind_param('s', $snr); $stmt->execute(); After this step I need to see if a row matched the query...but I have no idea how to write it, everyone here pretty much writes in mysql if I dont mention I want object oriented mysqli :S

    Read the article

  • Actionscript 2.0 Functions problem and somewhat "global" variable

    - by Joshua
    I have two problems. The first problem is with the following functions; when I call the function in (enterFrame), it doesn't work: onClipEvent (load) { function failwhale(levelNum) { _root.gotoAndStop("fail"); failFrom = levelNum; } function guardSightCollision(guardName, guardSightName) { if (_root.guardName.guardSightName.hitTest(_x, _y+radius, true)) { failwhale(1); } if (_root.guardName.guardSightName.hitTest(_x, _y-radius, true)) { failwhale(1); } if (_root.guardName.guardSightName.hitTest(_x-radius, _y, true)) { failwhale(1); } if (_root.guardName.guardSightName.hitTest(_x+radius, _y, true)) { failwhale(1); } } } onClipEvent (enterFrame) { guardSightCollision(guard1, guard1Sight); } Why doesn't it work?... The second problem lies in the failFrom variable: function failwhale(levelNum) { _root.gotoAndStop("fail"); failFrom = levelNum; } How do I make failFrom a "global" variable in that it can be accessed anywhere (from actionscript in frames and even movieclips)...Right now, when I try to trace failFrom in a different frame, it is "undefined".

    Read the article

  • C++ overloading virtual = operator

    - by taz
    Hello, here is the code for my question: class ICommon { public: virtual ICommon& operator=(const ICommon & p)const=0; }; class CSpecial : public ICommon { public: CSpecial& operator=(const CSpecial & cs) { //custom operations return *this; } }; CSpecial obj; Basically: I want the interface ICommon to force it's descendants to implement = operator but don't want to have any typecasts in the implementation. The compiler says "can't instantiate an abstract class. Any help/advice will be appreciated.

    Read the article

  • Method return values and exceptions

    - by dnagirl
    I have an interface called iIncident which defines a single method when(). when() should return a DateTime object. I'm trying to decide what to do if $object->when() has no DateTime to return as might be the case just after an object is instantiated and before all its properties are set. My choices are: return false throw some kind of Exception return some default DateTime like '9999-01-01' My inclination is to go with an Exception since $object really can't act as an incident until it knows when it occurred. I don't want to return a default DateTime because it complicates comparisons and it's not true. And I don't really want to return false because then I have to check for it every time I call the method- but if that is the preferred method, I guess I will. Is throwing an exception the best way? And is there a predefined exception type I should use (none of the SPL ones struck me as particularly appropriate- but that might just indicate my lack of experience)?

    Read the article

  • Flash AS3: automate property assignment to new instance from arguments in constructor

    - by matt lohkamp
    I like finding out about tricky new ways to do things. Let's say you've got a class with a property that gets set to the value of an argument in the constructor, like so: package{ public class SomeClass{ private var someProperty:*; public function SomeClass(_someProperty:*):void{ someProperty = _someProperty; } } } That's not exactly a hassle. But imagine you've got... I don't know, five properties. Ten properties, maybe. Rather then writing out each individual assignment, line by line, isn't there a way to loop through the constructor's arguments and set the value of each corresponding property on the new instance accordingly? I don't think that the ...rest or arguments objects will work, since they only keep an enumerated list of the arguments, not the argument names - I'm thinking something like this would be better: for(var propertyName:String in argsAsAssocArray){this[propertyName] = argsAsAssocArray[propertyName];} ... does something like this exist?

    Read the article

  • How do you keep application logic separate from UI when UI components have built-in functionality?

    - by Al C
    I know it's important to keep user interface code separated from domain code--the application is easier to understand, maintain, change, and (sometimes) isolate bugs. But here's my mental block ... Delphi comes with components with methods that do what I want, e.g., a RichText Memo component lets me work with rich text. Other components, like TMS's string grid not only do what I want, but I paid extra for the functionality. These features put the R in RAD. It seems illogical to write my own classes to do things somebody else has already done for me. It's reinventing the wheel [ever tried working directly with rich text? :-) ] But if I use the functionality built into components like these, then I will end up with lots of intermingled UI and domain code--I'll have a form with most of my code built into its event handlers. How do you deal with this issue? ... Or, if I want to continue using the code others have already written for me, how would you suggest I deal with the issue?

    Read the article

  • Is there a design pattern for injecting methods into a class?

    - by glenn I.
    I have a set of classes that work together (I'm coding in javascript). There is one parent class and a number of child classes that are instantiated by the parent class. I have a number of clients of these classes that each need to add on one more methods to the parent or child classes. Rather than having each client inherit from these classes, which is doable but messy because of the child classes, I am having these clients pass functions into the parent class when they instantiate the main class. The main class creates the methods dynamically and the clients can call the methods like they were there all along. My questions are: is this a sensible thing to do? what would the design pattern be for what I am doing?

    Read the article

  • Address calling class

    - by Samuel
    I have an abstract class Moveable with the method abstract void move() which is extended by the class Bullet and the abstract class Character, and Character is extended by the class Survivor and the class Zombie. In Survivor and Bullet the move() method doesnt require any parameters while in the class Zombie the move() method depends on the actual position of the survivor. The survivor and multiple zombies are created in the class Gui. I wanted to access the survivor in Zombie - what's the best way of doing this? In Gui i wrote a method getSurvivor() but i don't see how to access this method in Zombie? I am aware that as a workaround i could just pass a [Survivor survivor] as parameter in move() and ignore it in Bullet and Survivor, but that feels so ... bad practice.

    Read the article

  • Actionscript 2.0 Functions problem

    - by Joshua
    I have two problems. The first problem is with the following functions; when I call the function in (enterFrame), it doesn't work: onClipEvent (load) { function failwhale(levelNum) { _root.gotoAndStop("fail"); failFrom = levelNum; } function guardSightCollision(guardName, guardSightName) { if (_root.guardName.guardSightName.hitTest(_x, _y+radius, true)) { failwhale(1); } if (_root.guardName.guardSightName.hitTest(_x, _y-radius, true)) { failwhale(1); } if (_root.guardName.guardSightName.hitTest(_x-radius, _y, true)) { failwhale(1); } if (_root.guardName.guardSightName.hitTest(_x+radius, _y, true)) { failwhale(1); } } } onClipEvent (enterFrame) { guardSightCollision(guard1, guard1Sight); } Why doesn't it work?... The second problem lies in the failFrom variable: function failwhale(levelNum) { _root.gotoAndStop("fail"); failFrom = levelNum; } How do I make failFrom a "global" variable in that it can be accessed anywhere (from actionscript in frames and even movieclips)...Right now, when I try to trace failFrom in a different frame, it is "undefined".

    Read the article

  • Am I trying to Implement Multiple Inheritance. How can I do this.

    - by Shantanu Gupta
    I have created a class say A which has some functions defined as protected. Now Class B inherits A and class C inherits B. Class A has private default constructor and protected parameterized constructor. I want Class B to be able to access all the protected functions defined in Class A but class C can have access on some of the functions only not all the functions and class C is inheriting class B. How can I restrict access to some of the functions of Class A from Class C ? EDIT: namespace Db { public Class A { private A(){} protected A(string con){assign this value} protected DataTable getTable(){return Table;} protected Sqlparameters setParameters(){return parameter;} } } namespace Data { public Class B:A { protected B():base("constring"){} protected DataTable output(){return getTable();} protected sqlparameter values(param IDataParameter[] parameter){} } } namespace Bsns { public Class C:B { protected C():base(){} protected DataTable show() {return values(setparameter());} } } EDIT I think what I am trying to do here is Multiple inheritance. Please check. Class A { //suppose 10 functions are declared } Class B:A { //5 functions declared which are using A's function in internal body } Class C:B { //using all functions of B but require only 4 functions of A to be accessible by C. }

    Read the article

  • Dependency Injection & Singleton Design pattern

    - by SysAdmin
    How do we identify when to use dependency injection or singleton pattern. I have read in lot of websites where they say "Use Dependency injection over singleton pattern". But I am not sure if I totally agree with them. For my small or medium scale projects I definitely see the use of singleton pattern straightforward. For example Logger. I could use Logger.GetInstance().Log(...) But, instead of this, why do I need to inject every class I create, with the logger's instance?.

    Read the article

  • how to integrate Zend Framework MVC with existing site

    - by Joel
    Hi guys, So I'm slowly tackling OO and Zend Framework and their MVC process in particular. I have an existing website and web-based calendar application that was designed by me, but coded by a different person and done procedurally. I understand that it will be very difficult for my application to ever be completely OO without a full re-write, and I'm fine with that. I have a lot of updates and modifications I want to do in the future, so I'm wanting to start replacing some of the basic components (login, authentication. etc) now, and continue to learn as I go. Again, I'm really a newbie at programming and OO. What I'm wondering is if I'm wanting to incorporate the Framework, then would I just first drop my whole site into the /public folder of the Framework and then start pulling functionality out from there?

    Read the article

  • In what circumstances are instance variables declared as '_var' in 'use fields' readonly?

    - by Pedro Silva
    I'm trying to understand the behavior of the fields pragma, which I find poorly documented, regarding fields prefixed with underscores. This is what the documentation has to say about it: Field names that start with an underscore character are made private to the class and are not visible to subclasses. Inherited fields can be overridden but will generate a warning if used together with the -w switch. This is not consistent with its actual behavior, according to my test, below. Not only are _-prefixed fields visible within a subclass, they are visible within foreign classes as well (unless I don't get what 'visible' means). Also, directly accessing the restricted hash works fine. Where can I find more about the behavior of the fields pragma, short of going at the source code? { package Foo; use strict; use warnings; use fields qw/a _b __c/; sub new { my ( $class ) = @_; my Foo $self = fields::new($class); $self->a = 1; $self->b = 2; $self->c = 3; return $self; } sub a : lvalue { shift->{a} } sub b : lvalue { shift->{_b} } sub c : lvalue { shift->{__c} } } { package Bar; use base 'Foo'; use strict; use warnings; use Data::Dumper; my $o = Bar->new; print Dumper $o; ##$VAR1 = bless({'_b' => 2, '__c' => 3, 'a' => 1}, 'Foo'); $o->a = 4; $o->b = 5; $o->c = 6; print Dumper $o; ##$VAR1 = bless({'_b' => 5, '__c' => 6, 'a' => 4}, 'Foo'); $o->{a} = 7; $o->{_b} = 8; $o->{__c} = 9; print Dumper $o; ##$VAR1 = bless({'_b' => 8, '__c' => 9, 'a' => 7}, 'Foo'); }

    Read the article

  • java protected method accessibility

    - by JavaUser
    In the below code the Consumer class can access the protected method of Parent class.How is it possible since there is no relation between Parent and Consumer class.Please explain class Parent { public void method1(){ System.out.println("PUBLIC METHOD"); } private void method2(){ System.out.println("PRIVATE METHOD"); } protected void method3(){ System.out.println("PROTECTED METHOD"); } } public class Consumer { public static void main(String[] args){ Parent parentObj = new Parent(); parentObj.method1(); //parentObj.method2(); parentObj.method3(); } } Thanks

    Read the article

  • PHP 5.3: Late static binding doesn't work for properties when defined in parent class while missing in child class

    - by DavidPesta
    Take a look at this example, and notice the outputs indicated. <?php class Mommy { protected static $_data = "Mommy Data"; public static function init( $data ) { static::$_data = $data; } public static function showData() { echo static::$_data . "<br>"; } } class Brother extends Mommy { } class Sister extends Mommy { } Brother::init( "Brother Data" ); Sister::init( "Sister Data" ); Brother::showData(); // Outputs: Sister Data Sister::showData(); // Outputs: Sister Data ?> My understanding was that using the static keyword would refer to the child class, but apparently it magically applies to the parent class whenever it is missing from the child class. (This is kind of a dangerous behavior for PHP, more on that explained below.) I have the following two things in mind for why I want to do this: I don't want the redundancy of defining all of the properties in all of the child classes. I want properties to be defined as defaults in the parent class and I want the child class definition to be able to override these properties wherever needed. The child class needs to exclude properties whenever the defaults are intended, which is why I don't define the properties in the child classes in the above example. However, if we are wanting to override a property at runtime (via the init method), it will override it for the parent class! From that point forward, child classes initialized earlier (as in the case of Brother) unexpectedly change on you. Apparently this is a result of child classes not having their own copy of the static property whenever it isn't explicitly defined inside of the child class--but instead of throwing an error it switches behavior of static to access the parent. Therefore, is there some way that the parent class could dynamically create a property that belongs to the child class without it appearing inside of the child class definition? That way the child class could have its own copy of the static property and the static keyword can refer to it properly, and it can be written to take into account parent property defaults. Or is there some other solution, good, bad, or ugly?

    Read the article

< Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >